child 初始化后,parent 组件对 child DOM 的操作导致 ExpressionChangedAfterItHasBeenCheckedError

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

我想在 child 组件初始化后从 parent 组件对 child 组件进行一些操作。

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 到 StackBlitz 复制

编辑:

如果我将 setTimeout 添加到 parent 组件,它就可以工作。没有setTimeout我能实现吗?

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

您为此使用了 detectionChanges

constructor(private _cd: ChangeDetectorRef){}

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

  }