Angular ngModel with dynamic parameter

114 views Asked by At

In this Angular example, the ngModel binding does not work. Can someone let me understand why? and if so, What is the best way to do it?

(note that the binding uses a dynamic key)

ts:

constructor() {  this.days = { day1:'data', day2:'data2', day3:'data3...' }}

html:

<div *ngFor="let i of [1,2,3]">
   <span> {{days['day'+i]}}</span>
   <input type="text" [(ngModel)]="days['day'+i]" />
</div>

Thank you!

3

There are 3 answers

0
corsaro On BEST ANSWER

ngModel binding is not working because the ngFor directive creates a new scope for each iteration, and the days object is not being updated correctly within that scope.

To fix this issue, you can use an array to store the values for each day instead of using a dynamic key.

constructor() {
  this.days = ['data', 'data2', 'data3'];
}

<div *ngFor="let day of days; let i=index">
  <span> {{day}}</span>
  <input type="text" [(ngModel)]="days[i]" />
</div>
0
Tushar On

You might missed importing FormsModule

Check this: https://stackblitz.com/edit/angular-ahcs6h?file=src%2Fmain.ts

0
Yassin Mo On

you need to import the FormsModule module into your Angular app

 import { FormsModule } from '@angular/forms';