Home > Mobile >  Angular display own datas for each dynamic arrayForm
Angular display own datas for each dynamic arrayForm

Time:04-17

I have a dynamics ng-select and input through an arrayForm.

HTML:

<ng-container formArrayName="bottles">
      <div >
        <div >
          <ng-container *ngFor="let bottle of getBottles.controls; let i=index">
            <div [formGroup]="bottle" style="display: flex">
              <label for="alias-{{ i }}">Produit:</label>
              <ng-select id="productInput" (change)='selectTest($event, i)'
                         [items]="test[0] | keyvalue" bindLabel="value.name" bindValue="value.quantity" formControlName="product"></ng-select>
              <label for="bottleQuantity">Bottles needed: </label>
              <input *ngFor="let bott of bottles" style="height: 26px" id="bottleQuantity" type="bottleQuantity" formControlName="bottleQuantity"/><div for="alias-{{ i }}" style="color: green" *ngIf="itemSelected">(Qty: {{itemSelected}})</div>
              <span  style="cursor:pointer; color: red" *ngIf="getBottles.controls.length > 1" type="button addClass" (click)="removeBottle(i)">delete</span>
            </div>
          </ng-container>
          <span  style="cursor:pointer; color: green" (click)="addBottlesInput()">add_circle</span>
        </div>
      </div>
    </ng-container>

What i'd like is to display the own quantity of bottles for each dynamic field using index. But i don't know how to perform this using index (or an easier way ? )

<div for="alias-{{ i }}" style="color: green" *ngIf="itemSelected">(Qty: {{itemSelected}})</div>

See an example here StackBliz

Thank you for help :)

CodePudding user response:

As you want to show the quantity for the selected product per row:

  1. Need an array to store the selected product.
public itemsSelected: any[] = [];
  1. When a new row is added, you need to add the empty object into itemsSelected array.
public addBottlesInput = () => {
  ...

  this.itemsSelected.push({});
};
  1. When selecting a product for each row, you need to update the object in itemsSelected by index.
public selectTest = (event, i) => {
  if (event) {
    event.index = i;
    console.log('SELECTED', event);
    this.itemsSelected[i] = event.value;
  } else {
    this.itemsSelected[i] = {};
  }
};
  1. Lastly, in HTML, you need to get the object from itemsSelected by index. Use ?. (optional chaining) to safe get the quantity, especially for the case when the product is deselected.
<div style="color: green">
    (Qty: {{ itemsSelected[i]?.quantity }})
</div>

Or

<div style="color: green" *ngIf="itemsSelected[i]">
    (Qty: {{ itemsSelected[i].quantity }})
</div>

Sample Demo on StackBlitz

  • Related