2016-10-10 107 views
2

我想要控制組件的子實例,並且不能通過錯誤。我試圖沿着從this issue的答案。無法訪問父組件中的@ViewChildren

父組件Sequence包含子組件SequenceStep。父包含以下聲明:

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

然後我試圖做一些關於孩子:

ngAfterViewInit() { 
    this.steps.changes.subscribe(steps => { 
     console.log(steps); 
    }); 
} 

我得到的錯誤是:

metadata_resolver.js:639 Uncaught Error: Can't construct a query for the property "steps" of "Sequence" since the query selector wasn't defined.

SequenceSequenceStep組件都在其@Component裝飾器中定義了它們的選擇器(分別爲sequencesequence-step)。

我在做什麼錯在這裏?

+1

你能在重生中重現嗎? –

+0

@GünterZöchbauer對不起,我花了一段時間來重新創建plnkr,但這裏是:https://plnkr.co/edit/tusSBpbmyoG6TQTcV2i0?p=preview它不工作(請參閱控制檯) - 問題是:代碼是否正確? – user776686

回答

1

有幾件事情

  • 如果您通過從外面的孩子,他們是含量不孩子。 @ViewChild()僅適用於直接添加到組件模板的子項。

    @ContentChildren()作品上transcluded內容:

    @ContentChildren(TheChild) kids: QueryList<TheChild>; 
    
  • this.kids.changes()只通知有關初始化後的變化。 因此剛剛訪問this.kids直接ngAfterViewInit()然後subsribe得到通知後話了改變

    ngAfterViewInit() { 
        this.myKidsCount = this.kids.length; 
        this.cdRef.detectChanges(); 
    
        this.kids.changes.subscribe(kids => { 
         this.myKidsCount = kids.length; 
        }); 
    } 
    
  • 當變化檢測引起的變化角度不一樣。 ngAfterViewInit()被更改檢測調用,這就是爲什麼this.myKidsCount = this.kids.length會導致異常。

要解決我祈求變化檢測更改屬性myKidsCount後明確:

constructor(private cdRef:ChangeDetectorRef){} 

ngAfterViewInit() { 
    this.myKidsCount = this.kids.length; 
    this.cdRef.detectChanges(); 
} 

Plunker example

2

您是否嘗試將引號添加到@ViewChildren參數中?

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

+1

引用僅用於查詢模板變量名稱,查詢組件或指令類型時不需要使用引號。 –

+0

謝謝你的提示。 – lmetdaoui

+0

這對我有用 –

1

這個問題可以與SequenceStep的進口,檢查的類名相關的導入行。

+0

同意。另外,如果您有與父組件相同的文件中定義的指令(ViewChild),則指令定義必須在第一位。 – Miller

0

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

爲我工作。 Angular 4.X.X Angular CLI 1.X.X