1
votes

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.
1
Try to remove name attribute in input tag and use only. [(ngModel)]="store.Address1" only. Because [(ngModel)] contain name attribute itself. - Sanoj_V
I tried this and got the following error: If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions. Example 1: <input [(ngModel)]="person.firstName" name="first"> Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}"> I also tried {ngModelOptions]="{standalone: true}" and the error goes away, but editing one iteration updates all again. - Sung Chae
Can you try name="{{'store.'+i+'.address1'}}" this. - Sanoj_V
are you sure? can't replicate the issue, i created a stackblitz for this stackblitz.com/edit/angular-cehugw - John Velasquez
I think there is form tag inside loop causing error you can try to set Id attribute using i in form tag also. - Sanoj_V

1 Answers

0
votes

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)