在子组件初始化之后,我想对子组件的父组件进行一些操作。
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');
})
}
答案 0 :(得分:2)
您为此使用了detectionChanges
:
constructor(private _cd: ChangeDetectorRef){}
ngAfterViewInit() {
this.childComponent.domMethod('boo');
this._cd.detectChanges();
}