I am trying to add Datatables plugin (datatables.net) facility with my angualar 6 project. I am not sure how should I include the necessary css, js and other required files
Get JSON data from API url
Now you have to play in two components only one is html & other is .ts file
sample.Component.html
<table id="_zonetable" class="row-border hover" datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger">
<thead>
---
</thead>
<tbody>
<tr *ngFor="let item of ArrayResponse ; let i=index">
</tr>
</tbody>
</table>
now come to .ts file like sample.Component.ts
import { Component, OnInit ,OnDestroy} from '@angular/core';
import { Subject } from 'rxjs';
import { DataTableDirective } from 'angular-datatables';
declare var $: any;
now in the export :
export class UtilityComponent implements OnDestroy, OnInit {
dtElement: DataTableDirective;
dtOptions: DataTables.Settings = {};
dtTrigger: Subject<any> = new Subject();
ngOnInit(): void {
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: 10
};
ngOnDestroy(): void {
// Do not forget to unsubscribe the event
this.dtTrigger.unsubscribe();
if ($.fn.DataTable.isDataTable( '#_zonetable' )) {
// // call the loader
$('#_zonetable').dataTable().api().destroy();
}
}
rerender(): void {
this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
// Destroy the table first
dtInstance.destroy();
// Call the dtTrigger to rerender again
// this.dtTrigger.next();
});
}
ServiceFunction() {
this.ArrayResponse=[];
if ($.fn.DataTable.isDataTable( '#_zonetable' )) {
// // call the loader
$('#_zonetable').dataTable().api().destroy();
}
this.availservice.JsonAPi()
.subscribe((json) => {
this.ArrayResponse = json; //here you will get JSON response
// Calling the DT trigger to manually render the table
// debugger;
if ($.fn.DataTable.isDataTable( '#_zonetable')) {
// // call the loader
$('#_zonetable').dataTable().api().destroy();
}
this.dtTrigger.next();
console.log(this.ArrayResponse);
setTimeout(() => {
$('.overlaysv').hide();
}, 2000);
});
}
I got DataTables working by doing the following:
angular.json
"styles": [
"src/styles.css",
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"node_modules/datatables.net-dt/css/jquery.dataTables.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.js",
"node_modules/datatables.net/js/jquery.dataTables.js"
]
app.module.ts
import {DataTablesModule} from 'angular-datatables';
imports: [
...
DataTablesModule
]
You may have to stop and re-serve to see changes.