Reactive forms - disabled attribute
In my case with Angular 8. I wanted to toggle enable/disable of the input depending on the condition.
[attr.disabled]
didn't work for me so here is my solution.
I removed [attr.disabled]
from HTML and in the component function performed this check:
if (condition) {
this.form.controls.myField.disable();
} else {
this.form.controls.myField.enable();
}
I have been using [attr.disabled]
because I still like this template driven than programmatic enable()/disable() as it is superior IMO.
Change
<md-input formControlName="id" placeholder="ID" [disabled]="true"></md-input>
to
<md-input formControlName="id" placeholder="ID" [attr.disabled]="true"></md-input>
If you are on newer material change md-input
to mat-input
.
You can enable/disable a form control by using the following methods:
control.disable() or control.enable()
If that did not work for you can use a directive
import { NgControl } from '@angular/forms';
@Directive({
selector: '[disableControl]'
})
export class DisableControlDirective {
@Input() set disableControl( condition : boolean ) {
const action = condition ? 'disable' : 'enable';
this.ngControl.control[action]();
}
constructor( private ngControl : NgControl ) {
}
}
Then you could use it like this
<input [formControl]="formControl" [disableControl]="disable">
<button (click)="disable = true">Disable</button>
<button (click)="disable = false">Enable</button>
This technique is described here:
https://netbasal.com/disabling-form-controls-when-working-with-reactive-forms-in-angular-549dd7b42110
Hope it helps
I found that I needed to have a default value, even if it was an empty string. So this:
this.registerForm('someName', {
firstName: new FormControl({disabled: true}),
});
...had to become this:
this.registerForm('someName', {
firstName: new FormControl({value: '', disabled: true}),
});
See my question (which I don't believe is a duplicate): Passing 'disabled' in form state object to FormControl constructor doesn't work