Can't get to @ViewChildren in parent component

不羁的心 提交于 2019-12-01 00:20:41
Günter Zöchbauer

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<TheChild>;
    
  • 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

Have you tried adding quotes to your @ViewChildren arg?

@ViewChildren('SequenceStep') steps: QueryList<SequenceStep>;

This issue can be related to the import of SequenceStep, check the class name of the related import row.

@ViewChildren('SequenceStep') steps: QueryList<SequenceStep>;

Worked for me. Angular 4.X.X Angular CLI 1.X.X

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