Doubt about NgFor

0

Good evening guys,

I would like to have one select interact with the other and both have a NgFor that lists inside the option tags. The problem is that for the second select list to load I need the index of the first select.

Code:

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

@Component({
  selector: 'app-root',
  template: '<div>
  < p > Selecionar um select, para depois o outro.</p>
  < div >
  <select name="">
  <option value="" *ngFor="let lista of lista; let i=index" id= "{{i}}" >
  {{ lista.cliente }}
  </option>
  < /select>
  < p > Outro Select, deve conter os produtos do cliente selecionado no select anterior < /p>
    < select >
    <option value="let produto of lista" >
      {{ produto.produtos }}
</option>
  < /select>
  < /div>
  < /div>'
})

export class AppComponent implements OnInit {

  public lista: any = [{
      cliente: 'Rodolpho',
      produtos: [{
        nome: 'Sony PS4'
      }, {
        nome: 'Nintendo Switch'
      }]
    },
    {
      cliente: 'Gabriela',
      produtos: [{
        nome: 'Xbox One'
      }]
    }

  ];

  ngOnInit() {

  }

}

I do not know if my question was clear, but basically I need to select an item from the array and the index I use to put it in the second ngFor to load the corresponding products from the selected client.

    
asked by anonymous 11.08.2017 / 03:59

1 answer

1

Your first select will be fed by this initial list and the second select will be fed by another array (still empty). When the user selects the item in this first select, you call a function that will assign list [index] .product to the array that feeds the second select.

@Component({
  selector: 'my-app',
  template: 
 '
  <select (change)="onChange($event.target.value)">
  <option *ngFor="let item of lista; let i = index" [value]="i">
  {{item.cliente}}
  </option>
  </select>
  <select>
  <option *ngFor="let prod of produto">
  {{prod.nome}}
  </option>
  </select>
'

})

class MyApp {
  produto: Array<any>;
  lista: any = [{
      cliente: 'Rodolpho',
      produtos: [{
        nome: 'Sony PS4'
      }, {
        nome: 'Nintendo Switch'
      }]
    },
    {
      cliente: 'Gabriela',
      produtos: [{
        nome: 'Xbox One'
      }]
    }
  ];

onChange(valor) {
     this.produto = this.lista[valor].produtos;
  }

Follow sniped.

link

    
11.08.2017 / 05:36