Home > Enterprise >  Angular Table Delete Operation
Angular Table Delete Operation

Time:10-01

In my app, I have a list where the user can add to and delete elements from it. My problem is, when I click an element (it can be in the middle, at the end etc.), it deletes the first element of the list. And when I refresh the page, I can see the previously 'deleted' elements. Like I haven't deleted anything. Here is my code. What's wrong with it and how should I fix it?

HTML:

<button mat-icon-button>
  <mat-icon (click)="deleteWorkItem(row)">block</mat-icon>
</button>

TS:

deleteWorkItem(row: IProduct, index: number) {

  let supplierProduct: ISupplierProduct = {
    Supplier: {
      SupplierId: this.SupplierId
    },
    Product: {
      ProductId: row.ProductId
    }
  };

  this.confirmDialogRef = this._dialog.open(FuseConfirmDialogComponent, {
    disableClose: false
  });
  this.confirmDialogRef.componentInstance.confirmMessage = 'Ürünü silmek istiyor musunuz?';
  this.confirmDialogRef.afterClosed().subscribe(result => {
    if (result) {
      this._service.update('Supplier/DeleteSupplierProduct', supplierProduct).subscribe(response => {
        this._customNotificationService.Show('Ürün silindi', 'Tamam', 2);
      });
      let tempData = this.dataSource.data.slice(0);
      tempData.splice(index, 1);
      this.dataSource = new MatTableDataSource(tempData);
      this.EditIndex = undefined;

      this._products = this.dataSource.data;
      this.ProductChange.emit(this._products);
    }
  });


}

CodePudding user response:

You don't seem to pass index into deleteWorkItem method.

You need to declare a template variable within *ngFor as follows:

<div *ngFor="let row of data; let i = index">
  ...
  <button mat-icon-button>
    <mat-icon (click)="deleteWorkItem(row, i)">block</mat-icon>
  </button>
</div>
  • Related