0

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

家长:

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

1 回答 1

5

你有detectionChanges这个用途:

constructor(private _cd: ChangeDetectorRef){}

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

  }
于 2019-01-07T10:26:58.233 回答