Search code examples
angulartypescriptarraylistsplice

Remove object from arraylist displayed in a mat-table in Angular


From a mat-table I wish to remove a single row. This is what my button and (click) method looks like:

    <mat-cell *matCellDef="let element; let i = index">
          <button mat-raised-button color="warn" (click)="deleteApplication(i)">
               Delete
          </button>
     </mat-cell>

This is the function in my component.ts:

    deleteApplication(index: number){
    if (index > -1) {
        let removeIndex = this.applicationData.Items;
            this.applicationData.Items.splice(removeIndex[index], 1);
            removeIndex = new MatTableDataSource(removeIndex);
            console.log('new array:', removeIndex.filteredData);
       }
    }

The datasource is a arraylist from my DynamoDB database hosted on AWS. This is what the it looks like, in my console:

    {Items: Array(8), Count: 8, ScannedCount: 8}
    Count: 8
    Items: Array(8)
    0: {completed: false, candidate: "1", application: Array(3), timestamp: 1569837830615}
    1: {completed: false, candidate: "2", application: Array(3), timestamp: 1569837830615}
    2: {completed: false, candidate: "3", application: Array(3), timestamp: 1569837830615}
    3: {completed: false, candidate: "4", application: Array(3), timestamp: 1569837830615}
    4: {completed: false, candidate: "5", application: Array(3), timestamp: 1569837830615}
    5: {completed: false, candidate: "6", application: Array(3), timestamp: 1569837830615}
    6: {completed: false, candidate: "7", application: Array(3), timestamp: 1569837830615}
    7: {completed: false, candidate: "8", application: Array(3), timestamp: 1569837830615}
    length: 8
    __proto__: Array(0)
    ScannedCount: 8
    __proto__: Object

My problem is that when I hit the delete button on a given row are:

  1. It is always index number 0 that get removed, even if I hit a row that is not on index 0

  2. My view doesn't render, i.e the deleted row does not disappear


Solution

  • splice() method's first parameter is the start index, the index at which to start changing the array.

    In your code shown below, you are not passing the index as first parameter, but the value at the index.

    this.applicationData.Items.splice(removeIndex[index], 1);
    

    Change that statement to pass the index.

    this.applicationData.Items.splice(index, 1);