【问题标题】:QueryList changes subscribe does not workQueryList 更改订阅不起作用
【发布时间】:2017-08-28 06:01:19
【问题描述】:

我在一个组件中有一个QueryList。我正在动态添加其他组件,这些组件将出现在QueryList 中,但是如果我订阅QueryListchanges,则不会发生任何事情。我以为是因为我订阅了ngAfterViewInit,但QueryListundefined 而在ngOnInit

Here I have the plunkr.

代码:

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

    @ViewChildren(ControlFactoryDirective) factories:
        QueryList<ControlFactoryDirective>
    
    ngAfterViewInit() {
      this.factories.changes.subscribe(() => {
        console.log('changed')
      })
    }
}

【问题讨论】:

    标签: angular typescript eventemitter


    【解决方案1】:

    问题是,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)
    }
    

    【讨论】:

    • 请注意,如果您覆盖 notifyOnChanges 方法,将不再发出 changes。除非您在覆盖的 notifyOnChanges 方法中手动发出一个值,否则我猜(我没有测试该假设)
    【解决方案2】:

    对查询列表中的对象进行更改后,您应该调用查询列表来通知更改。

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

    【讨论】:

    • 那我要在ControlFactoryDirectivecreate里面添加notifyOnChanges,但是我不能在那里添加...我想检测添加组件时的变化
    【解决方案3】:

    您也可以像这样添加startWith(undefined)

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

    这将立即触发订阅处理程序。

    【讨论】:

    • startWith(undefined) 现在已弃用,您应该使用startWith([undefined])
    • @yktoo 哦,不,我将不得不在很多地方修复它。我希望 Angular 能给我一个可观察的值 + 变化。也适用于 FormGroup.changes。
    猜你喜欢
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-05
    • 1970-01-01
    相关资源
    最近更新 更多