How to delete mat-row from mat-table material design

10,994

This is called from somewhere like a button. It lives on this main component for the members section that has child components that call it, including the html for this component. It passes the params from the table along with whatever else is needed for the service above it to work. I included it so you understand how the delete row in table code works in case that matters.

members.component.ts

  // --- DELETE ---

  public deleteMember(itemId) {
    return this.mainComponentService.deleteItem(
      this.dbTable,
      itemId,
      this.name1,
      this.name2,
      this.tableItemId,
      this.paginator,
      this.dataSource
    );
  }

The html that calls from click events.

members.component.html

<ng-container matColumnDef="options">
          <mat-header-cell *matHeaderCellDef> Options </mat-header-cell>
          <mat-cell *matCellDef="let row">
            <button (click)="viewProfile(row.member_id)">View</button>
            <button (click)="deleteMember(row.member_id)">Delete</button>
            <button (click)="editMember(row.member_id)">Edit</button>
          </mat-cell>
        </ng-container>

Now the delete meat. This lives on a higher level component, above sections such as members, projects, etc and is used by the top level components in those sections of the app. Saves a lot of copying and pasting!

Notice the deleteRowDataTable function below the main action. This removes the row from the data table so the user sees it removed after their action. The trick is delete it from the database AND delete the data from the dataSource object. This way the user doesn't have to refresh the dataSource from the db.

main-component.service.ts

// --- DELETE ---

  public deleteItem(dbTable, itemId, name1, name2, tableItemId, paginator, dataSource) {
    // Get name from record to be deleted to warn in dialog.
    this.dsData = dataSource.data;
    const record = this.dsData.find(obj => obj[tableItemId] === itemId);
    const name = 'Delete ' + record[name1] + ' ' + record[name2] + '?';
// Call the confirm dialog component
this.confirmService.confirm(name, 'This action is final. Gone forever!')
  .switchMap(res => {if (res === true) {
    return this.appService.deleteItem(dbTable, itemId);
  }})
  .subscribe(
    result => {
      this.success();
      // Refresh DataTable to remove row.
      this.deleteRowDataTable (itemId, tableItemId, paginator, dataSource);
    },
    (err: HttpErrorResponse) => {
      console.log(err.error);
      console.log(err.message);
      this.messagesService.openDialog('Error', 'Delete did not happen.');
    }
  );
  }

  // Remove the deleted row from the data table. Need to remove from the downloaded data first.

  private deleteRowDataTable (itemId, tableItemId, paginator, dataSource) {
    this.dsData = dataSource.data;
    const itemIndex = this.dsData.findIndex(obj => obj[tableItemId] === itemId);
    dataSource.data.splice(itemIndex, 1);
    dataSource.paginator = paginator;
  }

This service is skinny and lives at the top of the stack along with app.module, etc. Not part of your question but may be useful for a complete answer for someone.

app.service.ts

// ---- DELETES a single record. ----

  public deleteItem(dbTable: string, itemId: number):  Observable<any> {
    return this.http
      .delete(`${this.baseUrl}${dbTable}?ids=${itemId}`, {headers: this.headers});
  }
Share:
10,994
vadlamani
Author by

vadlamani

Updated on June 26, 2022

Comments

  • vadlamani
    vadlamani almost 2 years

    Currently am using angular material design mat-table. Kindly help me to delete a record of data from mat-table.

    Here is the code:

                <mat-table #table [dataSource]="dataSource" matSort slimScroll width="auto" height="450px" color="rgba(0,0,0,0.3)" size="3px">
                        <!-- modelName Column -->
                        <ng-container matColumnDef="modelname">
                        <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
                        <mat-cell *matCellDef="let element" data-toggle="modal" data-target="#deviceView"> <span>{{element.modelname}}</span> </mat-cell>
                        </ng-container>
    
                        <!-- modelNumber Column -->
                        <ng-container matColumnDef="modelnumber">
                        <mat-header-cell *matHeaderCellDef mat-sort-header> Number </mat-header-cell>
                        <mat-cell *matCellDef="let element" data-toggle="modal" data-target="#deviceView"> <span>{{element.modelnumber}}</span> </mat-cell>
                        </ng-container>
    
                        <!-- manufacturer Column -->
                        <ng-container matColumnDef="manufacturer">
                        <mat-header-cell *matHeaderCellDef mat-sort-header> Manufac </mat-header-cell>
                        <mat-cell *matCellDef="let element" data-toggle="modal" data-target="#deviceView"> <span>{{element.manufacturer}}</span> </mat-cell>
                        </ng-container>
    
                        <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
                        <mat-row *matRowDef="let row; columns: displayedColumns; let i = index;" id="{{row.uuid}}" (click)="displayData(row.uuid); deleterow(index)"></mat-row>
                    </mat-table>
    
                    <div class="table-page">
                        <mat-paginator [length]="length" [pageSize]="1000" (page)="pageEvent = $event; onPaginateChange($event)">
                        </mat-paginator>
                        <div *ngIf="!pageEvent" class="pageformat text-primary">
                            {{pageSize}} / {{length}}
                        </div>
    
    
                        <div *ngIf="pageEvent" class="pageformat text-primary">
                            <div *ngIf="pageEvent.length >= pageEvent.pageSize * pageEvent.pageIndex + pageEvent.pageSize">{{pageEvent.pageSize * pageEvent.pageIndex + pageEvent.pageSize}} / {{pageEvent.length}}</div>
                             <div *ngIf="pageEvent.length <= pageEvent.pageSize * pageEvent.pageIndex + pageEvent.pageSize">{{pageEvent.length}} / {{pageEvent.length}}</div>
                        </div>
                    </div>
    
                </div>
    

    Kindly check and let me know any suggestions.