Biding select with array item

9 Views Asked by At

When I bind some "select" tag with an array item, like: <select [(ngModel)]="list[itemIndex]">

If I click on some of the options, other "select" fields are affected.

I tried to link 2 "select" fields, the first one is supposed to let the user choose the quantity of dishes, and the second one is for choosing the dishes.

An Array representing the dishes will be created with the chosen length from the first "select" field, refering to the quantity of dishes.

Then, for each dish we'll get another "select" for choosing which dish the user wants.

To solve the problem I created another array of options:

<select id="selecting-length" [(ngModel)]="selectedOptionForListLength" (change)="makeListWithChosenLength()">
  <option [value]="''" disabled>How many dishes do you want?</option>
  <option *ngFor="let i of optionsForAmountOfDishes">{{ !i ? 'None' : i }}</option>
</select>

<section *ngIf="listWithChosenDishes.length">
  <h1>Opções</h1>
  <div *ngFor="let optionIndex of indexesOfChosenDishes">
<!--    <div *ngFor="let optionIndex = index of listWithChosenDishes">-->
    <label id="dish{{optionIndex}}">Dish {{optionIndex + 1}}</label>
    <select id="dish{{optionIndex}}" [(ngModel)]="listWithChosenDishes[optionIndex]" (change)="printCurrentChosenDishes()">
      <option *ngFor="let dish of dishesOptions">{{dish}}</option>
    </select>
  </div>
</section>

The commented row is the one with a problem, to check it out you can comment the row before that one and uncomment that.

Here goes the TS code:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular';
  optionsForAmountOfDishes: number[]
  selectedOptionForListLength: number | string
  dishesOptions: string[]

  indexesOfChosenDishes!: number[]
  listWithChosenDishes: any[]

  constructor() {
    this.selectedOptionForListLength = ''
    this.optionsForAmountOfDishes = Array.from({length: 11}, (_, i) => i)
    this.listWithChosenDishes = []
    this.dishesOptions = ['Acarajé', 'Pastel', 'Bolo', 'Coxinha', 'Cuscuz com leite']
  }

  makeListWithChosenLength() {
    let chosenLength = Number(this.selectedOptionForListLength)
    if (isNaN(chosenLength)) chosenLength = 0

    this.listWithChosenDishes = new Array(chosenLength)

    this.indexesOfChosenDishes = Array.from({length: chosenLength}, (_, i) => i)
  }

  printCurrentChosenDishes() {
    console.log(this.listWithChosenDishes)
  }
}

I just wanted to understand why that happens, can anyone explain? I don't think it's much of relevant to report as an Issue on Angular Github.

0

There are 0 best solutions below