angularangular5splicearray-splice

how to use splice in angular 5


I have created a table that displays data fetched from the database. The TS part that fetches the data looks something like:

this._appService.getVisitData().subscribe((data) => {
  this.checkinTemp = data;
  // Calling the DT trigger to manually render the table
  this.dtTrigger.next();
});

The table gets generated and I have added an edit and delete function, my view code:

<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover">

  <thead>
  <tr>
    <th>ID</th>
    <th>Visitor Name</th>
    <th>Department</th>
    <th>Purpose</th>
    <th>Schedule Date Time</th>
    <th>Entry Source</th>
  </tr>
  </thead>
  <tbody>
  <tr *ngFor="let data of checkinTemp">
    <td>{{data.id}}</td>
    <td>
      <a  (click)="viewCheckinData(data)"> {{data.f_name}} {{data.l_name}} </a>
      <span>
            <a  (click)="editCheckinData(data)">Edit</a>
        <a  (click)="confirmDelete(data)">Delete</a>
      </span>
    </td>
    <td>
      <span *ngIf="data.department == null || data.department == ''">N/A</span>
      <span *ngIf="data.department !== null ">{{data.department}}</span>
    </td>
    <td>
      <span *ngIf="data.purpose == null || data.purpose == ''">N/A</span>
      <span *ngIf="data.purpose !== null ">{{data.purpose}}</span>
    </td>
    <td>{{data.pre_check_in | date:'short'}}</td>
    <td>{{data.creator_id}}</td>
  </tr>

  </tbody>
</table>


<p-confirmDialog header="Confirmation" icon="fa fa-question-circle" width="425"></p-confirmDialog>

Now when the user presses delete the confirmDelete(data) gets called. The function in the TS file:

confirmDelete(item) {
  this.confirmationService.confirm({
    message: 'Are you sure you want to delete this Visitor?',
    header: 'Confirmation',
    accept: () => {
      this._appService.deleteCheckin(item.id).subscribe(res => {
        // Splice Or something so the page doesnt reload but the data gets removed from the view.
        this.flashMsg.flashMsg('success', 'Deleted', 'Visitor has been deleted.');
      },
      err => {
        this.flashMsg.flashMsg('error', 'Error', 'Visitor has not been deleted.');
      });
    },
    reject: () => {
    },
  });
}

Until now when I delete data, the data gets deleted and the confirmation message pops up, but the data is still displayed in the view until the page gets reloaded. Is there a way to remove the data from the table without the page loading? I looked up splice but had no luck using it in the code.


Solution

  • After you have successfully deleted your item from the server, you can delete it from the array using splice(...) like this:

    const index = this.checkinTemp.indexOf(item);
    this.checkinTemp.splice(index, 1);