Angular ViewChildren does not see all children from ngFor immediately

吃可爱长大的小学妹 提交于 2019-12-02 00:32:58

The standard way to be notified that the content of a QueryList has changed it to subscribe to its changes event in ngAfterViewInit:

@ViewChildren("internals") internals: QueryList<InternalComponent>;

ngAfterViewInit() {
  this.internals.changes.subscribe((list: QueryList<InternalComponent>) => {
    // The updated QueryList is available here (with list or with this.internals)
    this.doSomethingWithInternals(list);
    this.doSomethingWithNewInternal(list.last);
    ...
  });
}

The event handling above may be all you need. If you still want to implement the afterViewInit event in InternalComponent, you can pass a reference to the component as a parameter of the event:

export class InternalComponent implements AfterViewInit {
  @Output() afterViewInit = new EventEmitter<InternalComponent>();

  ngAfterViewInit() {
    this.afterViewInit.emit(this);
  }

}

and retrieve the component in the event handler:

(afterViewInit)="onAfterViewInit($event)"

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