typescript QueryList 更改订阅不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43183465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
QueryList changes subscribe does not work
提问by István
I have a QueryList
in a component. I am adding dynamically other components, that will be present in the QueryList
, but if I subscribe to the changes
of the QueryList
, nothing happens. I thought it is because I subscribed in ngAfterViewInit
, but the QueryList
is undefined
yet in ngOnInit
. Here I have the plunkr.
我有QueryList
一个组件。我正在动态添加其他组件,这些组件将出现在 中QueryList
,但如果我订阅changes
了QueryList
,则什么也不会发生。我想这是因为我在认购ngAfterViewInit
,但QueryList
就是undefined
还没有在ngOnInit
。在这里,我有 plunkr。
code:
代码:
@Component({
...
})
export class AppComponent {
@ViewChildren(ControlFactoryDirective) factories:
QueryList<ControlFactoryDirective>
ngAfterViewInit() {
this.factories.changes.subscribe(() => {
console.log('changed')
})
}
}
回答by Mikha
The thing is, the list that comes to your factories
property is already pre-populated. So you just don't have a chance to subscribe to its changes beforeit's populated for the first time. But all changes that happen later are coming through to your subscriber, of course.
问题是,您的factories
财产的列表已经预先填充。因此,在第一次填充之前,您没有机会订阅其更改。但是,当然,以后发生的所有更改都会传递给您的订阅者。
Here is the plunkrwith your example updated - notice that factories now has a setter which proves that it's prepopulated (you normally don't need it in a real app, that's for finding out only what value comes from the framework)
这是更新了示例的plunkr- 请注意,工厂现在有一个 setter 来证明它已预先填充(您通常在真正的应用程序中不需要它,这是为了仅找出来自框架的值)
I think it's a totally valid behavior. So in ngAfterViewInit
, loop over values in the QueryList and do the same thing you are about to do in the subscriber:
我认为这是一个完全有效的行为。因此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)
}
回答by Roman C
After you make a change to the objects in query list you should call query list to notify on changes.
在对查询列表中的对象进行更改后,您应该调用查询列表来通知更改。
update() {
this.factories.forEach(factory => {
console.log(factory.componentRef.instance.model.data = "alma")
// factory.()
this.factories.notifyOnChanges();
})
}