skip to Main Content

I’m currently working on an Angular project and I’m trying to implement a feature where clicking a button triggers the deletion of a specific entity by passing its ID to a TypeScript method. However, I’m having trouble passing the ID from the TypeScript method to the HTML button to trigger the deletion event.

Here’s my current setup:

HTML:

<button mat-raised-button class="btn" color="warn" (click)="deleteStaffByID()">
Delete

TypeScript:

deleteStaffByID(id: any) {
console.log("Delete working!");
try {
    this.staffService.deleteStaffDataByID(id).subscribe(data => {
        this.dataSource = data;
        alert("Staff deleted successfully!");
        // this.listStaff();
        console.log(data);
    });
} catch(err) {
    console.log("error in deleting the staff", err);
}

}

I’m unsure how to pass the ID from the HTML button to the deleteStaffByID() method in TypeScript. I’ve tried various approaches, including defining a different parameter in the TypeScript method, but none have been successful.

Could someone please guide me on how to properly pass the ID from the HTML button to the TypeScript method in this scenario? Any help would be greatly appreciated. Thank you!

2

Answers


  1. This is how you generally do it with using NgForOf

    Note the let-item

    import { Component } from '@angular/core';
    import { NgForOf } from '@angular/common';
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [NgForOf],
      template: `
        <ng-template ngFor let-item [ngForOf]="ids">
          <button (click)="onIdClick(item)">click {{ item }}</button>
        </ng-template>
      `,
    })
    export class ContainerComponent {
      ids = [1, 2, 3, 4];
    
      onIdClick(id: number) {
        console.log(id);
      }
    }
    
    Login or Signup to reply.
  2. Try to pass id into deleteStaffByID() function as below:
    Template Code:

    <table>
    <tr *ngFor="let staff of staffArray">
        <td>{{ staff.name }}</td>
        <td><button mat-raised-button class="btn" color="warn" 
        (click)="deleteStaffByID(staff.id)">Delete
        </td>
    </tr>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search