在 Angular 12 中使用反应式表单时,如何触发从我的 ts 文件中进行选择更改的事件

问题描述 投票:0回答:1

我有一个reactvie表单,我正在尝试从ts文件中绑定表单的选项,我的mat-select上有一个selectchange事件侦听器,当我更改或选择Ui中的选项时会触发该事件侦听器,但是当我尝试将选项绑定到 mat-select selectchange 事件未触发,任何人都可以帮助我如何触发它

很好地尝试了 this.form.get(formcontrolname).setvlue 但没有触发 selectchnage 事件。

我的垫子选择元素-----

将 ts 文件中的表单选项值设置为 ----

this.form.get(aliasName)?.setValue(formattedValue);

触发 matselect 更改事件时触发的函数

selectChangeDetected(事件: MatSelectChange, 属性: { [key: string]: string }): void { // 我的数据操作 }

angular forms rendering angular12
1个回答
0
投票

(selectionChange)
仅当您使用单击或键盘更改选择时才考虑。就像您使用事件
(input)
(keydown)

您需要订阅 valueChanges

ngOnInit()
{
   const aliasName=???
   this.form.get(aliasName).valueChanges.subscribe((res:any)=>{
       console.log(res)
   })
}

您还可以订阅表单中的任何更改

   this.form.valueChanges.subscribe((res:any)=>{
       console.log(res) //<--will be the value of your form
   })

订阅form.valueChanges,您可以使用以下方式检查哪些“属性”发生变化

this.form.valueChanges
  .pipe(
    startWith(this.form.value),
    pairwise(),
    map(([old, actual]: [any, any]) => {
      return Object.keys(old)
        .map((x) => ({ property: x, value: actual[x], old: old[x] }))
        .filter((x: any) => x.value != x.old)[0];
    })
  )
  .subscribe((res) => {
    console.log(res);
  });

或者(如果您不想要旧值)

this.form.valueChanges
  .pipe(
    startWith(this.form.value),
    pairwise(),
    map(([old, actual]: [any, any]) => {
      return Object.keys(old).reduce((a: any, b: string) => {
        return (
          a ||
          (actual[b] == old[b] ? null : { property: b, value: actual[b] })
        );
      }, null);
    })
  )
  .subscribe((res) => {
    console.log(res);
  });
© www.soinside.com 2019 - 2024. All rights reserved.