Raj
Raj

Reputation: 63

Input ngModel in *ngFor binds to same value for all inputs

<tbody>
    <tr *ngFor="let trxList of trxNumberList; let i= index">
        <td>{{i}}</td>
        <td>
            <input type="text" name="trxNumber-{{i}}" class="form-control" minlength="1" maxlength="20" [(ngModel)]="trxList.trxNumber" />
        </td>
    </tr>
</tbody>

This is my table body, When I key in first input box, all the other inputs are binding to this value. Image attached. Please help.

enter image description here

EDIT:

Component code:

trxNumberObj = new Transaction;

ngOnInit() { 
  for(var i= 0 ; i <= 10; i++ ){ 
    this.trxNumberObj.count = i; 
    this.trxNumberList.push(this.trxNumberObj); 
  } 
}

Upvotes: 5

Views: 4664

Answers (2)

AVJT82
AVJT82

Reputation: 73357

Picked from your comment, the following piece of code:

trxNumberObj = new Transaction;

ngOnInit() { 
  for(var i= 0 ; i <= 10; i++ ){ 
    this.trxNumberObj.count = i; 
    this.trxNumberList.push(this.trxNumberObj); 
  } 
}

This behavior in template is because objects are mutable in JS. So what you are doing now, is pushing the same object to the array, which means that all objects in the array have a reference to the same object. What you need to do is to push new objects in the array:

ngOnInit() { 
  for(var i= 0 ; i <= 10; i++ ){ 
    this.trxNumberList.push({count:i++});  // push new object every time!
  }
}

You seem that you have a model for your object, so adapt that accordingly in above code.

Upvotes: 4

Vikhyath Maiya
Vikhyath Maiya

Reputation: 3192

Use the following

<input type="text" name="trxNumber-{{i}}" class="form-control" minlength="1" maxlength="20" [(ngModel)]="trxNumberList[index].trxNumber" />

This should do the trick.Let me know if it doesnt

Upvotes: 5

Related Questions