RRB
RRB

Reputation: 2116

Get index of ngFor item and update value

I am trying to update the text values of input fields in my Angular template. The template data values are generated in an NgFor loop which gets values from a web service. Here is my template.

<ul *ngFor="let item of vals?.bu">
  <li>
    <table>
          <tr>
            <td><button type="button" class="btn btn-info">{{item?.id}}</button></td>
            <td><input type="text" [(ngModel)]="item.bcluster"></td>
            <td><input type="text" [(ngModel)]="item.bsector"></td>
            <td><button type="button" id={{item?.id}} (click)="update($event)">Update</button></td>
          </tr>
          <tr>
            <td></td>
            <td><input type="text" [(ngModel)]="item.bgroup"></td>
            <td><input type="text" [(ngModel)]="item.bunit"></td>
            <td><button type="button" id={{item?.id}} (click)="delete($event)">Delete</button></td>
          </tr>
      </table>

  </li>
</ul>

I now need to get the values of the fields i.e 'bcluster, bsector, bgroup, bunit' from the template into my TS file in order to call the update API call(via a click event on the update button), however when I try to get the values I get undefined because I am not get the exact line index. Im not sure how to do this.

Here is my TS file(just trying to get the values consoled out)

  update(event) {
    console.log(this.bcluster);
  }

Upvotes: 0

Views: 7843

Answers (3)

jitender
jitender

Reputation: 10429

You should pass item and index from the template something like

<ul *ngFor="let item of vals?.bu; let i = index;">
  <li>
    <table>
          <tr>
            <td><button type="button" class="btn btn-info">{{item?.id}}</button></td>
            <td><input type="text" [(ngModel)]="item.bcluster"></td>
            <td><input type="text" [(ngModel)]="item.bsector"></td>
            <td><button type="button" id={{item?.id}} (click)="update(item,i)">Update</button></td>
          </tr>
      </table>

  </li>
</ul>

Than in ts

update(item,idx) {
    //here idx will give you the index
    console.log(item.bcluster);
  }

Upvotes: 5

Chandani Patel
Chandani Patel

Reputation: 471

Update ul to define index

<ul *ngFor="let item of vals?.bu; let i = index">

and use i as your function parameter

Upvotes: 2

user4676340
user4676340

Reputation:

The syntax is

*ngFor="let item of vals?.bu; let i = index;"

You can now pass i to your function.

Upvotes: 1

Related Questions