Angular ViewChildren does not see all children from ngFor immediately

后端 未结 1 908
深忆病人
深忆病人 2021-01-22 02:31

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

相关标签:
1条回答
  • 2021-01-22 02:42

    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);
        ...
    }
    
    0 讨论(0)
提交回复
热议问题