After child has been initialised, operation from p

2020-01-30 02:21发布

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条回答
戒情不戒烟
2楼-- · 2020-01-30 02:41

you have use detectionChanges for this:

constructor(private _cd: ChangeDetectorRef){}

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

  }
查看更多
登录 后发表回答