I have a select control that I want to disable dynamically based on a condition:
this.activityForm = this.formBuilder.group({
docType: [{ value: '2', disabled: this.activeCategory != 'document' }, Validators.required]
});
However, docType doesn't become enabled even though at some point this.activeCategory becomes 'document'.
How do I fix this?
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.
We can use disable() and enable() method of FormControl . We can also call disable/enable function at runtime by using control[action]() method of FormControl . We need to pass action as 'disable' or 'enable'. We can also use [disabled]="true" binding to disable a form control.
Since I don't know how you're manipulating activeCategory
(maybe it's also a FormControl
?), I'll suggest the following approach:
You can use (change)
to detect when this.activeCategory
has changed, as below:
1 - If you're using ngModel
:
<input type="text" [(ngModel)]="activeCategory" (change)="checkValue($event)">
2 - If it's a FormControl
:
<input type="text" formControlName="activeCategory" (change)="checkValue($event)">
So, in component, you can manipulate the docType
control using disable/enable
methods:
checkValue(event: Event) {
const ctrl = this.activityForm.get('docType');
if (event.value === 'document') {
ctrl.enable();
} else {
ctrl.disable();
}
}
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