首页 > 解决方案 > 根据选择值禁用 Angular Reactive 表单输入

问题描述

我有一个表单(使用 Angular Material),我想根据选择值禁用一些输入字段。我的代码如下所示:

HTML

<mat-form-field class="someclass">
   <mat-select placeholder="Select payment method" formControlName="paymentMethod">
      <mat-option *ngFor="let payment of paymentMethodOptions" [value]="payment.value">
         {{payment.viewValue}}
      </mat-option>
   </mat-select>
</mat-form-field>

<mat-form-field class="someclass">
   <input matInput placeholder="Some input" formControlName="testInput">
</mat-form-field>

TS

paymentMethodOptions: payment[] = [
   { value: "opt-1", viewValue: "somevalue" },
   { value: "opt-2", viewValue: "anothervalue" }
];

paymentForm = new FormGroup({
   paymentMethod: new FormControl("", Validators.required),
   testInput: new FormControl({ value: "", disabled: true }, [
      Validators.required
   ])
});

testInput如果选择的值等于 ,我想禁用"opt-1"。我尝试了几个选项,但得到了不同的错误并且无法解决。有什么可行的解决方案吗?提前致谢!

标签: angularangular-materialangular-reactive-forms

解决方案


您可以收听valueChanges表单的事件:

this.paymentForm.valueChanges.subscribe((value) => {
  if(value.paymentMethod == 'opt-1'){
   this.paymentForm.controls['testInput'].disable();
  }else{
   this.paymentForm.controls['testInput'].enable();
  }
});

因此,每次select更改时,valueChanges都会调用事件,条件启动,它将启用或禁用 formControl。


推荐阅读