angulartypescriptangular-ngmodel

Angular ngModel with dynamic parameter


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!


Solution

  • 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>