Can't get to @ViewChildren in parent component

后端 未结 4 934
感动是毒
感动是毒 2021-01-06 17:30

I am trying to get control over the children instances of a component and can\'t go past an error. I am trying to follow along the answers from this issue.

The paren

4条回答
  •  隐瞒了意图╮
    2021-01-06 17:45

    There are a few things

    • If you pass children from the outside, they are content not children. @ViewChild() only works for children added to the template of a component directly.

      @ContentChildren() works on transcluded content:

      @ContentChildren(TheChild) kids: QueryList;
      
    • this.kids.changes() only notifies about changes after the initialization. Therefore just access this.kids directly in ngAfterViewInit() and then subsribe to get notified about later changes

      ngAfterViewInit() {
        this.myKidsCount = this.kids.length;
        this.cdRef.detectChanges();
      
        this.kids.changes.subscribe(kids => {
            this.myKidsCount = kids.length;
        });
      }
      
    • Angular doesn't like when change detection causes changes. ngAfterViewInit() is called by change detection, this is why this.myKidsCount = this.kids.length causes an exception.

    To work around I invoke change detection explicitly after changing the property myKidsCount:

    constructor(private cdRef:ChangeDetectorRef){}
    
    ngAfterViewInit() {
      this.myKidsCount = this.kids.length;
      this.cdRef.detectChanges();
    }
    

    Plunker example

提交回复
热议问题