【问题标题】:Angular Material Select, selectionChange not firing角度材质选择,selectionChange 未触发
【发布时间】:2020-08-13 16:32:12
【问题描述】:

我已经准备了示例(Angular Material Select):

Stackblitz

我在 ngOnInIt 上为 mat-select 设置了值,但 selectionChange 事件 是 不开火。每当我使用 value 属性将 value 设置为 mat-select 时,我想要那个 selectionChange 被解雇了,我想做一些工作 选择更改。

selectionChange 在手动用户选择时触发,而不是在设置值时触发。

为什么 selectionChange 事件没有触发?

还有其他事件或方法可以实现这一目标吗?

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    Demo selectionChange 事件仅在用户更改 html 元素而不是后端数据更改时触发。您可以使用Viewchild 作为手动调用函数的方式:

    @ViewChild("changeEl") el!: ElementRef;
    
        ngAfterViewInit(){
            this.selectedFood = this.foods[0].value;
            this.selectionChangeTax(this.el)
          }
    

    HTML:

    <h4>Basic mat-select</h4>
    <mat-form-field appearance="fill">
      <mat-label>Favorite food</mat-label>
      <mat-select (selectionChange)="selectionChangeTax($event)" #changeEl [(value)]="selectedFood">
        <mat-option *ngFor="let food of foods" [value]="food.value">
          {{food.viewValue}}
        </mat-option>
      </mat-select>
    </mat-form-field>
    

    【讨论】:

    • 调用 selectionChange 事件的另一种选择是什么?有什么活动吗?我不想显式调用 selectionChange
    【解决方案2】:

    这是预期的行为。但是我已经准备了 StackBlitz,我使用 RxJS 订阅选择中的新值。每当值更改时,订阅中的下一个回调将被触发。输出见console

    https://stackblitz.com/edit/angular-bhwtam-udkedb

    【讨论】:

      【解决方案3】:

      如果您想了解所有更改,可以使用 valueChange。

      在 ngOnInit 上

      this.myForm = this.formBuilder.group({ firstName: [this.firstName], lastName: [this.lastName] });
      
       this.myForm.controls['firstName'].valueChanges.subscribe(value => { console.log(value); });
      

      【讨论】:

      • 你能给我举个例子吗?因为我有 trien valueChange 事件,但它不起作用
      • 不,这是表单控件值更改事件。我想要垫选事件
      猜你喜欢
      • 1970-01-01
      • 2018-11-03
      • 2018-06-09
      • 2018-12-13
      • 2020-07-18
      • 2021-10-07
      • 2022-11-28
      • 1970-01-01
      • 2019-03-08
      相关资源
      最近更新 更多