Doubt about the Ngfor

Asked

Viewed 1,027 times

0

Good evening, everyone,

I would like to make a select interact with each other and both have an Ngfor that lists within the option tags. The problem is that for the list of the second select 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 don’t know if my doubt was clear, but basically I need to select an item of the array and the index I use to put in the second ngFor to load to the corresponding products of the selected customer.

  • Easy to do, boring to explain. Your first select will be fed by your initial list and the second select will be fed by another (still empty) array. When the user selects the item in that first select, vc calls a function q will assign list[Indice]. product to the q array feeds the second select.

1 answer

1


Your first select will be fed by your initial list and the second select will be fed by another (still empty) array. When the user selects the item in that first select, vc calls a function q will assign list[Indice]. product to the q array 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;
  }

Follows sniped.

https://codepen.io/ccastroelo/pen/JyJBMr

Browser other questions tagged

You are not signed in. Login or sign up in order to post.