Search code examples
htmlangulartypescriptangular-directivengfor

Retrieve ID of *ngFor elements in a table - Angular


I have a table wherein I've iterated 3 FA-icons inside Button tag using *ngFor, like the image shown here.

Table

I have given the 3 buttons separate IDs(viz. 1,2&3) to note which button is clicked. The buttons are Add, Edit and Delete. Although I'm sending it's ID through (click) event to the component. The function is not able to retrieve the ID every time the button is clicked. It retrieves the ID after random multiple clicks and not each time the button is clicked. I don't understand why it's behaving like this.

HTML:

<tbody>
    <tr *ngFor="let ABC of XYZ">
      <td>{{ABC.Records}}}</td>
      <td>
           <button id="1" (click)="fun($event)"><fa-icon [icon]="plussquare"></fa-icon></button>
           <button id="2" (click)="fun($event)" ><fa-icon [icon]="editfa"></fa-icon></button>
           <button id="3" (click)="fun($event)" ><fa-icon [icon]="trashfa"></fa-icon></button>
      </td>
    </tr>
</tbody>

.TS:

fun($event:any){
     console.log($event.target.id)
 }

All add buttons should have id 1, edit buttons should have id 2 and 3 for delete buttons.


Solution

  • Do you not just need 3 methods ?

     funEdit($event:any, yourVar){
         console.log($event.target.id)
     }
    funAdd($event:any, yourVar){
             console.log($event.target.id)
    }
    funDelete($event:any, yourVar){
             console.log($event.target.id)
    }
    

    That you will use like it :

    <button (click)="funAdd($event,ABC)"><fa-icon [icon]="plussquare"></fa-icon></button>
    <button (click)="funEdit($event,ABC)" ><fa-icon [icon]="editfa"></fa-icon></button>
    <button (click)="funDelete($event,ABC)" ><fa-icon [icon]="trashfa"></fa-icon></button>
     
    

    And passing your ABC var in second params to know the line