Array of array Model - Angular 2

2019-09-21 15:47发布

问题:

This is lead from the other post Nested Model - Angular 2

I have a scenario, where data object have multiple persons, each person can have multiple address. Showing address type in dropdown, when select address type full address is shown on text area.

<div *ngFor="let persons of data; let i = index">
    <div *ngFor="let person of persons; let j = index">
      <select [ngModel]="selectedAddress[j]" (ngModelChange)="selectedAddress[j] = $event">
        <option *ngFor="let address of person.addresses" [ngValue]="address">
            {{address.type}}
        </option>
      </select>
      <textarea [(ngModel)]="selectedAddress[j].address"></textarea>
    </div>
</div>

Each person is displayed in each div block. On selecting the drop down on div 'Person A'. Populates textarea in div 'Person B'. How to handle this scenario?

The previous post fixed issue around address collection within same parent div. Here issue is around persons collection. When you try to select Dropdown in Parent A, textarea being populated in Parent B as well.

回答1:

You can have a two dimensions array... but consider to do a refactor in order to get a cleaner implementation.

Initialize selectedAddress like: selectedAddress = [[]] and do so:

<div *ngFor="let persons of data; let i = index">
<div *ngFor="let person of persons; let j = index">
  <select [ngModel]="selectedAddress[i][j]" (ngModelChange)="selectedAddress[i][j] = $event">
    <option *ngFor="let address of person.addresses" [ngValue]="address">
        {{address.type}}
    </option>
  </select>
  <textarea [(ngModel)]="selectedAddress[i][j].address"></textarea>
</div>
</div>

I Don't know exaclty if (ngModelChange)="selectedAddress[i][j] = $event" updates that selectedAddress[i][j], if not, selectedAddress[i][j].address will crash. But I think if the last solution worked this has to work. If it crashes, con con init the array with empty object. But I repeat, this solution is getting a little bit tricky.



标签: angular