Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Angular Reactive form input based on selection value

I have a form (using Angular Material), and I want to disable some of the input fields based on selection values. My code looks as below:

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
   ])
});

I want to disable testInput if the value of the selection is equal to "opt-1". I've tried several options, but got different errors and couldn't solve it. Is there any working solution to this? Thanks in advance!

like image 260
Andrew Avatar asked Nov 21 '18 06:11

Andrew


People also ask

How do I turn off form control and keep value?

If you set disabled to true when you set up this control in your component class, the disabled attribute will actually be set in the DOM for you. We recommend using this approach to avoid 'changed after checked' errors. Example: form = new FormGroup({ first: new FormControl({value: 'Nancy', disabled: true}, Validators.


1 Answers

You'll can listen to the valueChanges event of the form :

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

So everytime the select changes , the valueChanges event is called , the conditions kick in and it will enable or disable the formControl.

like image 85
CruelEngine Avatar answered Sep 23 '22 05:09

CruelEngine