'Value' attribute in Angular is not applied to an <input> tag if i also add [(ngModel)]

59 Views Asked by At

I am working on a wizard form. The form have multiple steps (Personal, address...). All of this steps represents child component wrapped in a parent component that use NgRx Store to save the data typed by the user.

The goal is to load that data every time the user want to go back in the wizard form. All the logic with the NgRx works but I don't understand why the 'value' attribute applied to the tag does not work if i am using [(ngModel)] to the same <input> tag.

Here is a piece of code:

<input
      type="text"
      placeholder="name"
      value="{{inputData.name}}"
      [(ngModel)]="inputDataTemplate.name"
      (ngModelChange)="updateName(inputDataTemplate.name)"
/>

inputData is an Observable that display the data from the NgRx Store.

If the <input> doesn't contain the [(ngModel)] and (ngModelChange) attributes the data is displayed:

<input
      type="text"
      placeholder="name"
      value="{{inputData.name}}"
/>
2

There are 2 best solutions below

0
Kshitij On
<input
  type="text"
  placeholder="name"
  [(ngModel)]="inputData.name"
  (ngModelChange)="updateName(inputDataTemplate.name)"/>

[(ngModel)] is used for 2-way binding. input field renders with default value of ngModel variable. If you change the input field value then, it updates ngModel variable automatically. Make sure you are using correct variable name for ngModel binding.

0
Hezy Ziv On

Remove the value attribute from your input field and use only [(ngModel)] for two-way binding.

in component

// Assuming you have an observable like inputData$
inputData$.subscribe(data => {
  this.inputDataTemplate.name = data.name;
});

template

<input
  type="text"
  placeholder="name"
  [(ngModel)]="inputDataTemplate.name"
  (ngModelChange)="updateName(inputDataTemplate.name)"
/>