Umesh M Gowda
Umesh M Gowda

Reputation: 121

Angular 5 : how to update datatable after deleting a row

I am able to delete the selected row from the database asynchronously, but how can I update in the view part without refreshing the page. Here is my component code.

import { Component, OnInit, Input } from '@angular/core';
import { Router } from "@angular/router";
import { UsersService } from 'app/+users/users.service';
import { dateFormatPipe } from 'app/shared/custom-pipe/date-format.pipe';
import { FlashMessagesService } from 'angular2-flash-messages';

declare var $:any;

@Component({
  selector: 'app-manage-user',
  templateUrl: './manage-user.component.html'  
})

export class ManageUserComponent implements OnInit{

  constructor(
    private usersService: UsersService, 
    private route: Router,
    private _flash: FlashMessagesService,
  ) {}

  tableData: any;

  ngOnInit() {  
    this.fetchTableData();
  }

  fetchTableData(){
    this.tableData = {
      ajax: (data, callback, settings) => {
        this.usersService.getUsers(0).subscribe(data => {
          if(data.success){
              callback({
                aaData: data.data

              });
          } else {
            alert(data.msg);
          }
        },
        error => {
            alert('Internal server error..check database connection.');
        });

      },
      columns: [ 
          { 
            render: function (data, type, row, meta) {
                return meta.row + 1;
            }
          },
          {
            data: function (name) { return name.firstname+ ' ' + name.lastname}
          }, 
          {data: 'email'},
          {data: 'user_role'}, 
          {data: function(data){           
            return new dateFormatPipe().transform(data.created_at); 
          }},
          {          
            render: function (data, type, row) {
              return `<button type="button" class="btn btn-warning btn-xs edit" data-element-id="${row._id}">
              <i class="fa fa-pencil-square-o"></i> Edit</button>
              <button type="button" class="btn btn-danger btn-xs delete" data-element-id="${row._id}">
              <i class="fa fa-pencil-square-o"></i> Delete</button>`;
            }
          }
      ],
      buttons: [
          'copy', 'pdf', 'print'
      ]
    };

    document.querySelector('body').addEventListener('click', (event)=> {
        let target = <Element>event.target; // Cast EventTarget into an Element
        if (target.tagName.toLowerCase() === 'button' && $(target).hasClass('edit')) {
          this.user_edit(target.getAttribute('data-element-id'));          
        }
        if (target.tagName.toLowerCase() === 'button' && $(target).hasClass('delete')) {
          this.user_delete(target.getAttribute('data-element-id'));          
        }   
    });

  }  

  user_delete(user_id){
    this.usersService.deleteUserById(user_id).subscribe(data => {      
      if(data.success){
        // On successful deletion of the data from the database I need to update the datatable so that the deleted row will vanish.

      } else {
        this._flash.show(data.msg , { cssClass: 'alert alert-warning fade in', timeout: 4000 });  
      }
    },
    error => {
        this._flash.show('Internal server error..check database connection.' , { cssClass: 'alert alert-warning fade in', timeout: 4000 });
    });
  }

  user_edit(user_id){
    console.log("user edit:" +user_id);
  }

}

As of now, I am able to delete the row from the database but after deleting it, the deleted row is still visible. If I refresh the page the deleted row isn't visible. How can I update the datatable asynchronously?

Upvotes: 4

Views: 4842

Answers (1)

Ramya
Ramya

Reputation: 46

try using *ngIf directive on table.

<div class="widget-body no-padding" *ngIf="tData">
    <sa-datatable [options]="tableData" paginationLength="true" tableClass="table table-striped table-bordered table-hover" width="100%">
        <thead>
            <tr>
                <th data-hide="phone"> ID </th>
                <th data-class="expand"> Name </th>
                <th data-hide="phone,tablet"> Email </th>
                <th data-hide="phone,tablet"> Role </th>
                <th data-hide="phone,tablet"> join Date </th>
                <th data-hide="phone,tablet"> Action </th>
            </tr>
        </thead>
    </sa-datatable>
</div>

By default make tData: boolean = false; and while calling API make it true so that if there is any data then the table will be rendered.

fetchTableData(){
 this.tData = true;
 ...
}

and while calling the delete function make tData false and call the API like bellow

user_delete(user_id) {
    this.tData= false;
    this.usersService.deleteUserById(user_id).subscribe(data => {
      if (data.success) {
        // On successful deletion of the data form database i need to update the datatable so that the deleted row will be vanished.
        this.fetchTableData();
        this._flash.show(data.msg, { cssClass: 'alert alert-info fade in', timeout: 4000 });
      } else {
        this._flash.show(data.msg, { cssClass: 'alert alert-warning fade in', timeout: 4000 });
      }
    },
      error => {
        this._flash.show('Internal server error..check database connection.', { cssClass: 'alert alert-warning fade in', timeout: 4000 });
      });
  }

on successful delete call fetchTableData(); which intern load the updated data and shown in a table.

Upvotes: 3

Related Questions