如何防止 Angular Material mat-select 更改选项?

How to prevent Angular Material mat-select change option?

<mat-form-field appearance="fill">
  <mat-label>Favorite food</mat-label>
  <mat-select [formControl]="topFormControl" [(value)]="topSelectValue">
    <mat-option *ngFor="let food of foods" [value]="food" >
      {{food.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>
  ngOnInit(): void {
    this.topFormControl.valueChanges
      .pipe(
        startWith(this.topFormControl.value),
        pairwise()
      ).subscribe(
        ([old, cur]) => {
          if(
            //cur.value === 's'
          ){
            //prevent user select the option, force mat-select still shows the old option.
          }
        }
      );
  }

  foods: Food[] = [
    { value: 's', viewValue: 'Steak' },
    { value: 'p', viewValue: 'Pizza' },
    { value: 't', viewValue: 'Tacos' },
  ];

当用户select Steak in Favorite food,防止mat-select显示Steak但保留旧选项时,有什么解决办法吗?

非常感谢。

您可以在 FormControl 上使用 setValue 方法并将 emitEvent:false 作为第二个参数传递以停止再次触发 valueChanges。

 ngOnInit(): void {
        this.topFormControl.valueChanges
          .pipe(
            startWith(this.topFormControl.value),
            pairwise()
          ).subscribe(
            ([old, cur]) => {
              if(
                //cur.value === 's'
              ){
                this.topFormControl.setValue(curr.value,{emitEvent:false})
              }
            }
          );
      }