Grant Curell
Grant Curell

Reputation: 1783

Adding formControlName in Angular breaks "value" in input control

I have a form and am trying to figure out why as soon as I add the attribute "formControlName" value stops rendering. I ended up boiling things down to a very simple example:

This:

<mat-form-field [style.width.px]=400>
    <mat-label>Port Redirects</mat-label>
    <input matInput placeholder="Ex. Pizza" value="Sushi">
</mat-form-field>

will render Sushi as expected:

enter image description here

However as soon as you add formControlName like this:

<mat-form-field [style.width.px]=400>
    <mat-label>Port Redirects</mat-label>
    <input matInput formControlName="port_list" placeholder="Ex. Pizza" value="Sushi">
</mat-form-field>

the value just up and disappears:

enter image description here

The official documentation says this is the way to do it so I'm at a loss as to why adding formControlName breaks things. Aside from the value field not working correctly, the form is otherwise just fine. Does everything I would expect it to. Is there a trick I'm missing?

Upvotes: 0

Views: 1863

Answers (1)

julianobrasil
julianobrasil

Reputation: 9377

Once you use any FormControl directive on an element, you should set its value using the directive instead of the value attribute. This is true for Reactive and Template-driven forms.

In that case you can do:

_form = new FormGroup({
 port_list: new FormControl();
});

ngOnInit() {
  setTimeout(() => 
    this._form.patchValue({port_list: 'Sushi'}));
}

Stackblitz demo

Notice that if you use the two approaches (set the value attribute and the form control), during initialization, value is set later, so it overrides the control value in the HTML element and doesn't update the form control value itself (likely a bug in the component). That's why I used a setTimeout: just to schedule the control setting value statement to be executed in the next turn of the event loop.

Upvotes: 1

Related Questions