子级初始化之后,子级DOM上父组件的操作导致ExpressionChangedAfterItHaHasBeenCheckedError [英] After child has been initialised, operation from parent component on child DOM causes ExpressionChangedAfterItHasBeenCheckedError
本文介绍了子级初始化之后,子级DOM上父组件的操作导致ExpressionChangedAfterItHaHasBeenCheckedError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在子组件初始化之后,我想对子组件的父组件进行一些操作。
I'd like to make some operation from parent component on child component after child component has been initialised.
export class ParentComponent implements AfterViewInit {
@ViewChild('child') childComponent: ChildComponent;
ngAfterViewInit() {
this.childComponent.domMethod('boo');
}
}
<p>parent</p>
<app-child #child></app-child>
孩子:
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
的情况下实现它?
If I add setTimeout
to the parent component, it works. Can I achieve it without setTimeout
?
ngAfterViewInit() {
setTimeout(() => {
this.childComponent.domMethod('boo');
})
}
推荐答案
您已将 detectionChanges
用于
constructor(private _cd: ChangeDetectorRef){}
ngAfterViewInit() {
this.childComponent.domMethod('boo');
this._cd.detectChanges();
}
这篇关于子级初始化之后,子级DOM上父组件的操作导致ExpressionChangedAfterItHaHasBeenCheckedError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文