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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With