After child has been initialised, operation from parent component on child DOM causes ExpressionChangedAfterItHasBeenCheckedError

纵饮孤独 提交于 2019-11-26 14:56:42

问题


I'd like to make some operation from parent component on child component after child component has been initialised.

Parent:

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>

Link to StackBlitz for reproduction

Edit:

If I add setTimeout to the parent component, it works. Can I achieve it without setTimeout?

  ngAfterViewInit() {
    setTimeout(() => {
      this.childComponent.domMethod('boo');
    })
  }

回答1:


you have use detectionChanges for this:

constructor(private _cd: ChangeDetectorRef){}

ngAfterViewInit() {
      this.childComponent.domMethod('boo');
      this._cd.detectChanges();

  }


来源:https://stackoverflow.com/questions/54072065/after-child-has-been-initialised-operation-from-parent-component-on-child-dom-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!