Home > Blockchain >  Angular - Bind each *ngFor input to specific button and extract data
Angular - Bind each *ngFor input to specific button and extract data

Time:10-18

So I have the following problem:

I have this html:

<tbody>
    <tr *ngFor='let product of productList'>
    <td>{{product.name}}</td>
    <td>{{product.quantity}}</td>
    <td>{{product.price}}</td>
    <td  *ngIf="isLoggedInConfirmed()">
      <div [formGroup]="quantityInput">
        <input type="number" min="0" formControlName="quantity">
      </div>
    </td>
    <td  *ngIf="isLoggedInConfirmed()">
        <button>Add to cart</button>
    </td>
  </tr>
</tbody>

... which constructs a table with inputs and buttons. How can I assign each button to extract the data from the input next to it?

Currently, this implementation does not work properly. Each button gets information from the last input where a number was added.

enter image description here

From the screenshot - lets say that the last entered input is 1 on the last row. All the buttons will get 1 as information. If I enter new number on the 2nd row all buttons will get this number.

How can overcome this issue, so that each button gets the value of the input next to it?

CodePudding user response:

For this to work you will need your inputs to have multiple controls. For that you would need to change your HTML as follows (Assuming you are going to use reactive controls)

<tbody *ngIf="productForm" [formGroup]="productForm">
  <tr *ngFor='let product of productList; let i = index'>
  <td>{{product.name}}</td>
  <td>{{product.price}}</td>
  <td  *ngIf="isLoggedInConfirmed()">
      <input type="number" min="0" formControlName="quantity{{i}}">
  </td>
  <td  *ngIf="isLoggedInConfirmed()">
      <button>Add to cart</button>
  </td>
  </tr>
</tbody>

Note that I have changed formControlName="quantity" to formControlName="quantity{{i}}"

In ts you need to build the form group accordingly

const group: any = {};

this.productList.forEach((product, i) => {
  group['quantity'   i] = new FormControl(product.quantity || '', Validators.required);
});
this.productForm = new FormGroup(group);

Here is the sample stackblitz

  • Related