2

I am using angular-datatables in my Angular app. I need to refresh the datatable when data changes (say, when a form is filled and submitted). The equivalent jQuery code is

$('#my-datatable').DataTable.ajax.reload().

I am using Angular 7. And here is the link of the library that I am using.

Patricio Vargas
  • 5,236
  • 11
  • 49
  • 100
Kihats
  • 3,326
  • 5
  • 31
  • 46
  • I strongly suggest you to not use that library. It uses jquery and using jquery is not good pratices in angular apps. There a lot of libraries that provide table functionalities – Patricio Vargas Nov 07 '19 at 06:04
  • @devpato, kindly direct me to the libraries you are talking about in the comment above – Kihats Nov 07 '19 at 06:45
  • @devpato, on the similar stackoverflow answer you've provided, seems it's using jQuery of which I could simply do `$('#my-datatable').DataTable.ajax.reload()` and it's working. – Kihats Nov 07 '19 at 06:48
  • https://www.primefaces.org/primeng/#/table https://material.angular.io/components/table/overview – Patricio Vargas Nov 07 '19 at 07:00

1 Answers1

5

dtInstance.ajax.reload(). You can create a reload() function.

Try like this:

import { DataTableDirective } from 'angular-datatables';

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

reload() {
  this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
    dtInstance.ajax.reload()
  });
}
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
  • how does it identify a particular datatable? Say I have multiple datatables in the same page – Kihats Nov 07 '19 at 06:51
  • You need to use `@ViewChildren(DataTableDirective); dtElements: QueryList` – Adrita Sharma Nov 07 '19 at 06:56
  • And this.dtElements.forEach((dtElement: DataTableDirective) => { // Get the instance and do your stuff }); – Adrita Sharma Nov 07 '19 at 06:57
  • If you provide a stackbiltz,can show working demo as I didn't try the above code in the comment. In one of my projects I created 3 child component for 3 tables to avoid this scenerio – Adrita Sharma Nov 07 '19 at 07:02