I have a strange behaviour of @ViewChildren corresponding to children components generated by ngFor. @ViewChildren query does not see element standing in array for a quite long
The standard way to be notified that the content of a QueryList
has changed is 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);
...
}