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.
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
.
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();
}
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
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