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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:25:04  来源:igfitidea点击:

QueryList changes subscribe does not work

angulartypescripteventemitter

提问by István

I have a QueryListin a component. I am adding dynamically other components, that will be present in the QueryList, but if I subscribe to the changesof the QueryList, nothing happens. I thought it is because I subscribed in ngAfterViewInit, but the QueryListis undefinedyet in ngOnInit. Here I have the plunkr.

我有QueryList一个组件。我正在动态添加其他组件,这些组件将出现在 中QueryList,但如果我订阅changesQueryList,则什么也不会发生。我想这是因为我在认购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 factoriesproperty 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();
  })
}