Sung Chae
Sung Chae

Reputation: 51

Angular 6 - ngModel in ngFor is updating every item in array

I started learning Angular 6 a couple weeks ago, so I'm still new to this.

I've been trying to update two-way bind fields in an array of objects.

Here is my array initialized in

store.component.ts:

store_list = [{
    Address1: 'add1',
    Address2: 'test',
    City: ''
},{Address1: 'aaaa',
    Address2: 'bbbb',
    City: 'cccc'}];

    trackStore(index: number, obj: any): any {
    return index;
}

store.component.html:

<div *ngFor="let store of store_list; let i=index; trackBy: trackStore;">
  <mat-card class="store-card" mat-elevation-z8>
     <mat-card-content>
      <form class="example-form">
        <mat-form-field class="address-street">
          <input matInput [(ngModel)]="store_list[i].Address1" placeholder="Street Address" name="store.{{i}}.address1" required>
        </mat-form-field>            
        <mat-form-field class="address-street">
          <input matInput [(ngModel)]="store.Address2" placeholder="Address Line 2" name="store.{{i}}.address2" required>
        </mat-form-field>
       </form>
     </mat-card-content>
  </mat-card>
</div>

I tried binding two different ways to ngModel to see if either would work. They both behave the same way though.

When I have an array of 3 stores and update Address 1 or Address 2 on ANY one of those stores, all 3 store Address 1 fields update.

Most of the research online resulted in 3 solutions, none of which has worked so far.

  1. Include index in "name" attribute to have a unique field name.
  2. Use trackBy, I also tried using a unique id in the store_list array and returning it through the custom trackBy function and it didn't work.
  3. Don't use ngModel in ngFor.

Upvotes: 1

Views: 3979

Answers (1)

Sanoj_V
Sanoj_V

Reputation: 2986

Try this in for loop and remove trackby inside *ngFor: <input matInput [(ngModel)]="store.Address1" placeholder="Street Address" required> Because [(ngModel)] contain name attribute itself. See the documentation here: (angular.io/api/forms/NgModel)

Upvotes: 1

Related Questions