2017-04-03 52 views
2

我在組件中有一個QueryList。我正在動態添加其他組件,這些組件將出現在QueryList中,但如果我訂閱了QueryListchanges,則不會發生任何情況。我認爲這是因爲我在ngAfterViewInit訂閱,但QueryListundefined還在ngOnInitHere I have the plunkrQueryList更改訂閱不起作用

代碼:

@Component({ 
    ... 
}) 
export class AppComponent { 

    @ViewChildren(ControlFactoryDirective) factories: 
     QueryList<ControlFactoryDirective> 

    ngAfterViewInit() { 
     this.factories.changes.subscribe(() => { 
     console.log('changed') 
     }) 
    } 
} 

回答

6

事情是,你的factories屬性的列表已經預先填充。所以你只是沒有機會訂閱之前的更改它是第一次填充。但是,當然,以後發生的所有更改都會通過您的訂閱者進行。

以下是plunkr,並更新了您的示例 - 注意,工廠現在擁有一個證明它已預填充的setter(通常不需要它在真實應用程序中,這僅用於查找框架中的值)

我認爲這是完全有效的行爲。因此,在ngAfterViewInit,遍歷在QueryList價值觀和你約在用戶做同樣的事情:

ngAfterViewInit() { 
    this.processChildren(); // first call to processChildren 

    this.factories.changes.subscribe(_ => 
     this.processChildren() // subsequent calls to processChildren 
); 
} 

private processChildren(): void { 
    console.log('Processing children. Their count:', this.factories.toArray().length) 
} 
1

後進行了更改,以在查詢列表中的對象,你應該打電話查詢列表通知上的變化。

update() { 
    this.factories.forEach(factory => { 
    console.log(factory.componentRef.instance.model.data = "alma") 
    // factory.() 
    this.factories.notifyOnChanges(); 
    }) 
} 
+0

然後,我要補充的'ControlFactoryDirective'的'create'的'notifyOnChanges',但我無法在那裏添加...我想在添加組件時檢測更改 –