子级初始化之后,子级DOM上父组件的操作导致ExpressionChangedAfterItHaHasBeenCheckedError

时间:2019-01-07 09:56:50

标签: angular angular-changedetection

在子组件初始化之后,我想对子组件的父组件进行一些操作。

父母:

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');
    })
  }

1 个答案:

答案 0 :(得分:2)

您为此使用了detectionChanges

constructor(private _cd: ChangeDetectorRef){}

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

  }