QueryList更改订阅不起作用
问题描述:
我在组件中有一个QueryList
。我正在动态添加其他组件,这些组件将出现在QueryList
中,但如果我订阅了QueryList
的changes
,则不会发生任何情况。我认为这是因为我在ngAfterViewInit
订阅,但QueryList
是undefined
还在ngOnInit
。 Here I have the plunkr。QueryList更改订阅不起作用
代码:
@Component({
...
})
export class AppComponent {
@ViewChildren(ControlFactoryDirective) factories:
QueryList<ControlFactoryDirective>
ngAfterViewInit() {
this.factories.changes.subscribe(() => {
console.log('changed')
})
}
}
答
事情是,你的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)
}
答
后进行了更改,以在查询列表中的对象,你应该打电话查询列表通知上的变化。
update() {
this.factories.forEach(factory => {
console.log(factory.componentRef.instance.model.data = "alma")
// factory.()
this.factories.notifyOnChanges();
})
}
然后,我要补充的'ControlFactoryDirective'的'create'的'notifyOnChanges',但我无法在那里添加...我想在添加组件时检测更改 –