0

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?

3
  • You are trying to have angular reactive form, which works as like mentioned here angular.io/guide/reactive-forms#grouping-form-controls Commented Jun 5, 2020 at 2:59
  • I'm familiar - are they mutually exclusive? Can I not set a default value like I normally would when I use reactive forms? Commented Jun 5, 2020 at 3:00
  • formControlName must be used with a parent formGroup directive .. Take a look at the stackblitz here: stackblitz.com/edit/angular-mat-form-field-p6usms .. Here the value can be set also you can change but it won't store into the control for which you need to make a formGroup and set the formcontrol in ts file.. But as you are familiar I hope you know that steps.. Commented Jun 5, 2020 at 3:04

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.