Ionic (Angular) - ngModel inside an ngFor

Asked

Viewed 166 times

1

Good afternoon,

I would like an orientation, I am learning from Ionic and assembling an application, on my main page there is the following code:

    <form>

  <ion-card class="cardsIndex" *ngFor="let produto of produtos; let i = index">
    <img src="{{produto.imagem}}"/>
    <ion-card-header class="cardHeader">
      <ion-card-title><b>{{produto.nome}}</b></ion-card-title>
      <ion-label><b>Estoque:</b> {{produto.quantidade}}</ion-label>
    </ion-card-header>
    <ion-card-content class="cardsInputs">
      <ion-button (click)="comprarButton(produto.id)" >Comprar</ion-button>
      <ion-input class="inputHome" type="number" min="0" [(ngModel)]="comprarQtd" name="produto{{i+1}}" placeholder="Quantidade"></ion-input>
    </ion-card-content>
  </ion-card>

</form>

I’m consulting a json-server and getting product information. Each "Card" has a field for the purchase and the input field that will be placed the amount that the user wants to buy. However, when placing the value in any of the input fields, they all take the same value.

In the component class of this page, there is the variable:

comprarQtd: number;

I know what is wrong is that it is assigning to ALL fields the same value that is being indicated in this variable above. However, you would know how to guide me how I can assign each Input value to its given variable and it does not assign to all fields at the same time?

Thank you very much!

2 answers

1


If it were me I’d do it differently, take the value of input with a function and model with that value taken from the function, you can see the example working here:

HTML:

<ion-input class="inputHome" type="number" min="0" (input)="Qtd($event.target.value)" 
 placeholder="Quantidade"></ion-input>

TS:

Qtd(valor) {
  this.comprarQtd = valor;
}
  • Man, thank you so much for your help! I applied your example and helped me perfectly in what I needed! Thank you very much!

  • Jewel that helped man, success!

0

By the time you get your products from your backend you have to add this field for each respective product.

this.produtosService.pegarProdutos().subscribe(produtosResponse=>{
   this.produtos=produtosResponse.map(produto=>{return {...produto,comprarQtd: 0}}
}

Ai in your html you access the qntd respective that product

[(ngModel)]="produto.comprarQtd"
  • Thanks for the help! It sure is a way and gave me ideas!

Browser other questions tagged

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