Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing 'disabled' in form state object to FormControl constructor doesn't work

Tags:

angular

We've seen this before:

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 that is output with the warning:

  form = new FormGroup({
    first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
    last: new FormControl('Drew', Validators.required)
  });

But when I try to do it like it says, it doesn't work. So I search for the issue on SO, and I find a number of questions like this, but they all say to call FormControl.disable() manually. I'd like to not have to do that, but passing disabled in the 'form state object' to the constructor doesn't work. Why not?

Here is my code:

this.registerForm('someName', {
  firstName: new FormControl({disabled: true}),
});

This is not a duplicate of this question, as I was asking why something doesn't work that should, without an additional function call, or adding things to the template. And what I discovered through my answer is pretty key, and possibly an oversight in the design of Angular.

like image 319
BBaysinger Avatar asked Mar 09 '18 18:03

BBaysinger


People also ask

How do I turn off reactive dropdown?

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.


1 Answers

Actually, the reason it didn't work was that I did not have 'value' in my form state object. It should have been:

this.registerForm('someName', {
  firstName: new FormControl({value: '', disabled: true}),
});

See the reasoning for this requirement here: github.com/angular/angular/pull/10994#issuecomment-244195999

like image 123
BBaysinger Avatar answered Oct 21 '22 15:10

BBaysinger