BBaysinger
BBaysinger

Reputation: 6877

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

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.

Upvotes: 10

Views: 14230

Answers (1)

BBaysinger
BBaysinger

Reputation: 6877

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

Upvotes: 22

Related Questions