根据选择值禁用Angular Reactive表单输入

And*_*rew 5 angular-material angular angular-reactive-forms

我有一个表单(使用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>
Run Code Online (Sandbox Code Playgroud)

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
    ])
  });
Run Code Online (Sandbox Code Playgroud)

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

Cru*_*ine 5

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

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

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


Sid*_*era 4

您可以利用该selectionChange @Output属性MatSelect并做出相应的反应:

onSelectionChanged({value}) {
  console.log(value);
  if(value === 'opt-1') {
    this.paymentForm.get('testInput').disable();
  } else {
    this.paymentForm.get('testInput').enable();
  }
}
Run Code Online (Sandbox Code Playgroud)

并在模板中

<mat-select ... (selectionChange)="onSelectionChanged($event)">
Run Code Online (Sandbox Code Playgroud)

这是一个StackBlitz 示例供您参考。

注意:如果表单中的控件多于mat-select,则监听valueChanges整个表单的成本可能会很高,因为每次任何表单控件发生更改时都会触发此操作。我们关心的只是mat-select选择的变化。