【问题标题】:Can I use formControl valueChanges to detect changes to a mat-chip-list?我可以使用 formControl valueChanges 来检测对 mat-chip-list 的更改吗?
【发布时间】:2021-05-04 15:15:39
【问题描述】:

我有一个mat-chip-list,想检测它何时发生变化,即:添加或删除项目。

我希望我可以附加一个表单控件并利用 valueChanges observable 来实现这一点,即:

<mat-chip-list #chipList [formControl]="chipListCtrl">
chipListCtrl = new FormControl();
...
this.fruitCtrl.valueChanges.pipe(tap(value => console.log('fruitCtrl: ', value))).subscribe();

但是,这不会将任何内容记录到控制台。

参考Stackblitz,输入控件以这种方式成功工作,但芯片列表没有。

这可能吗?如果可以,我需要做什么才能让它工作?

【问题讨论】:

    标签: angular angular-material angular-reactive-forms


    【解决方案1】:

    筹码列表不会发出 valueChanges,因为您没有更新它的值。您正在更新 fruits 数组,它与您的 formControl 没有任何关联。

    我已经对您的stackblitz 进行了分叉,以便事件更新您的chipListCtrl 的值,而mat-chip-list 的内容正在使用chipListCtrl.value

    【讨论】:

      【解决方案2】:

      您不需要 formControl 来检测 mat-chip-list 中的更改。 根据文档 - https://material.angular.io/components/chips/api, 您可以直接使用(更改)事件发射器。

      @Output()
      变化:EventEmitter

      当所选芯片列表值已被用户更改时发出的事件。

      【讨论】:

      • 我已经尝试过了,但根本无法触发更改事件。甚至它的文档也是模棱两可的,因为它指的是选择 - '当用户更改 selected 芯片列表值时发出的事件。此外,如果我可以观察到这些变化,那就更方便了。在这里查看 stackblitz:stackblitz.com/edit/…
      猜你喜欢
      • 2019-01-25
      • 2016-12-16
      • 1970-01-01
      • 2018-12-29
      • 2021-07-12
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      • 2019-12-08
      相关资源
      最近更新 更多