I am trying to use the disabled
attribute from a formControl
. When I put it in the template, it works:
<md-input formControlName="id" placeholder="ID" [disabled]="true"></md-input>
But the browser alerts me:
It looks like you're using the disabled attribute with a reactive form directive. 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.required), last: new FormControl('Drew', Validators.required) });
So I put it in the FormControl
, and deleted from the template:
constructor(private itemsService: ItemsService) {
this._items = [];
this.myForm = new FormGroup({
id: new FormControl({value: '', disabled: true}, Validators.required),
title: new FormControl(),
description: new FormControl()
});
this.id = this.myForm.controls['id'];
this.title = this.myForm.controls['title'];
this.description = this.myForm.controls['description'];
this.id.patchValue(this._items.length);
}
But it does not work (it is not disabling the input
). What is the problem?
disabling of mat form fields is exempted if you are using form validation,so do make sure that your form field does not have any validations like(validators.required),this worked for me. for ex:
editUserPhone: new FormControl({value:' ',disabled:true})
this makes the phone numbers of user to be non editable.
I have been using
[attr.disabled]
because I still like this template driven than programmatic enable()/disable() as it is superior IMO.Change
to
If you are on newer material change
md-input
tomat-input
.I found that I needed to have a default value, even if it was an empty string for it to work. So this:
...had to become this:
See my question (which I don't believe is a duplicate): Passing 'disabled' in form state object to FormControl constructor doesn't work
Only who are using reactive forms : For native HTML elements [attr.disabled] will work but for material elements we need to dynamically disable the element.
Otherwise it will show in console warning message.
The beauty of reactive forms is you can catch values changes event of any input element very easily and at the same time you can change their values/ status. So here is the another way to tackle your problem by using
enable
disable
.Here is the complete solution on stackblitz.
Ultimate way to do this.