Disable Angular Reactive form input based on selection value
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.
You can leverage the selectionChange
@Output
property on MatSelect
and react accordingly:
onSelectionChanged({value}) {
console.log(value);
if(value === 'opt-1') {
this.paymentForm.get('testInput').disable();
} else {
this.paymentForm.get('testInput').enable();
}
}
And in template
<mat-select ... (selectionChange)="onSelectionChanged($event)">
Here's a Sample StackBlitz for your ref.
NOTE: In case there are more controls in your form than just mat-select
, listening to valueChanges
on the whole form could be expensive as this will get triggered every time there is a change in any of the form control. All we are concerned about is the change in the mat-select
selection change.
Though there are already answers provided, If any had stumbled with the same issue. You can directly disable a form field by directly accessing its control
Had created a Stackblitz demo link
<!-- INPUT FIELD -->
<mat-form-field formControlName="testInput">
<input matInput
placeholder="Some input"
[disabled]="paymentForm.get('paymentMethod').value === 'opt-1'"> // Disables the input once paymentMethod's formControlName value is opt-1
</mat-form-field>