4

I'm using angular 7 with angular-datatables. I'm tring to define a "rerender" button in order to reload data like in this example.

I don't understand what should I place in the render function:

My API function:

fn_getFavoriteTables() {

  this._getFavoriteTablesApiCall =  this.getFavoriteTablesService.getFavoriteTables(Number(localStorage.getItem('UserID')), Number(localStorage.getItem('BranchID'))).pipe(takeUntil(this.destroySubject$)).subscribe(x => {
        this.getFavoriteTables = x;
        this.dtTrigger.next();
    });

};

rerender function:

rerender(): void {
    this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
        // Destroy the table first 

        dtInstance.destroy();


        // Call the dtTrigger to rerender again
        this.dtTrigger.next();
    });
}

ngOnDestroy(): void {
  console.log('ngDestroy');
  // Do not forget to unsubscribe the event
  this.dtTrigger.unsubscribe();
}
devDan
  • 5,969
  • 3
  • 21
  • 40
Assaf Sela
  • 76
  • 1
  • 7

3 Answers3

4

This can also be done like this:

import { DataTableDirective } from 'angular-datatables';

dtElement: DataTableDirective;
dtInstance: Promise<DataTables.Api>;

rerender(): void  {
  this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
    dtInstance.ajax.reload()
  });
}
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
  • I have tried this solution but it cannot find the namespace DataTables.Api. I have imported DatatablesModule as well as types/datatablesnet and nothing... I]'m using version 9.0.2 of datatables –  Aug 10 '20 at 15:54
1

Found an answer that worked for me: this is the source site

 rerender(): void {
    this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
        // Destroy the table first 
        //debugger;
        var table = $('#favoriteTable').DataTable();

        $('#tableDestroy').on('click', function () {
            table.destroy();
        });

        dtInstance.destroy();

        this.fn_getFavoriteTables();

    });
}
Assaf Sela
  • 76
  • 1
  • 7
1

You can use the DataTable destroy() API to remove the table and re-use the dtTrigger to render the table again. Please check below link.

https://l-lin.github.io/angular-datatables/#/advanced/rerender

Sanjeev Chauhan
  • 3,977
  • 3
  • 24
  • 30