med morad
med morad

Reputation: 509

ngModel change multiple selects

I have a problem using ngModel on multiple selects. I use an array schedule to build a table, and in every td I put a select that I bind with the schedule entries.

The problem is that when I change the first select, the second one change also. and I can't understand why.

This is a working example on stackblitz: https://stackblitz.com/edit/angular-ivy-agbsye

enter image description here

Here is the app.component.ts file

export class AppComponent  {
  options = ["TC", "1BAC", "2BAC"]
  schedule = []
  constructor(){
    for(let i = 0; i < 7; i++){
      this.schedule[i]= [];
      for(let j = 0; j < 8; j++){
        this.schedule[i][j] = ''
      }
    }
  }
}

And this is the app.component.html file

<table>
  <tr *ngFor="let day of schedule;let i=index">
    <ng-container *ngFor="let hour of schedule[i];let j=index">
      <td>
      <select [(ngModel)]="schedule[i][j]">
            <option [ngValue]="''" selected>
            </option>
            <ng-container *ngFor="let level of options" >
            <option  [ngValue]="level">
              {{level}}
            </option>
            </ng-container>
          </select>
      </td>
      <td *ngIf="j==3" style="width:20px;height:20px;background:black"></td>
    </ng-container>
  </tr>
</table>

Upvotes: 0

Views: 176

Answers (1)

munleashed
munleashed

Reputation: 1685

You can also:

Add in template trackBy: 
<ng-container *ngFor="let hour of schedule[i];let j=index; trackBy:trackByFn">

Implement in component:
trackByFn(i) {return i}

Upvotes: 1

Related Questions