0

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!

5
  • 1
    What is the error you are getting? I checked the above code and it is running correctly. Commented Mar 23, 2023 at 10:57
  • 1
    I am not getting any error, but the input value is empty. I do not see the 'data' and 'data2' etc. Commented Mar 23, 2023 at 11:04
  • 1
    Have you imported FormsModule? Commented Mar 23, 2023 at 11:08
  • Sure. In your POC does it work as expected? Commented Mar 23, 2023 at 11:10
  • You can check the stackblitz link I posted below. Commented Mar 23, 2023 at 11:11

3 Answers 3

0

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>
Sign up to request clarification or add additional context in comments.

Comments

0

You might missed importing FormsModule

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

Comments

0

you need to import the FormsModule module into your Angular app

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

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.