我想在子组件初始化后从父组件对子组件进行一些操作。
家长:
export class ParentComponent implements AfterViewInit {
@ViewChild('child') childComponent: ChildComponent;
ngAfterViewInit() {
this.childComponent.domMethod('boo');
}
}
<p>parent</p>
<app-child #child></app-child>
孩子:
export class ChildComponent implements OnInit {
constructor(private readonly cdr: ChangeDetectorRef,) {
}
public term = '';
public items;
ngOnInit() {
this.items = [
{ name: 'foo' },
{ name: 'bar' },
{ name: 'baz' },
{ name: 'boo' },
{ name: 'zoo' },
];
}
domMethod(value: string) {
// const input = document.getElementById('childInput') as HTMLInputElement;
// input.value = value;
this.term = value;
this.cdr.markForCheck(); // <-- enabling this line cause ExpressionChangedAfterItHasBeenCheckedError
}
}
<p>child</p>
<input type="text" id="childInput" [(ngModel)]="term">
<ul>
<li *ngFor="let item of items | search: term">{{item.name}}</li>
</ul>
链接到StackBlitz进行复制
编辑:
如果我添加setTimeout
到父组件,它可以工作。我可以在没有的情况下实现它setTimeout
吗?
ngAfterViewInit() {
setTimeout(() => {
this.childComponent.domMethod('boo');
})
}