Hi,
I have a question about Refresh/Reinitialize DataTable.
Im using Metronic v9.0.4 with Angular. The DataTable component is working fine and now I want to implement function to fetch new data and view new fetched data. How to refresh/reinitialize the DataTable when a button was clicked without reload the page?
Hi
You need to:
- Destroy the existing DataTable instance.
- Fetch the new data from your API.
- Reinitialize the DataTable with the new dataset.
Here some example datatable code:
import { Component, OnInit, ViewChild } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { DataTableDirective } from "angular-datatables";
import { Subject } from "rxjs";
@Component({
 selector: "app-my-table",
 templateUrl: "./my-table.component.html",
 styleUrls: ["./my-table.component.scss"]
})
export class MyTableComponent implements OnInit {
 @ViewChild(DataTableDirective, { static: false }) dtElement!: DataTableDirective;
 dtOptions: DataTables.Settings = {};
 dtTrigger: Subject<any> = new Subject<any>();
 tableData: any[] = [];
 constructor(private http: HttpClient) {}
 ngOnInit(): void {
 this.dtOptions = {
 pagingType: "full_numbers",
 pageLength: 10,
 processing: true
 };
 this.loadData();
 }
 loadData() {
 this.http.get<any[]>("YOUR_API_ENDPOINT").subscribe(data => {
 this.tableData = data;
 this.dtTrigger.next(null); // Initialize DataTable
 });
 }
 refreshTable() {
 this.http.get<any[]>("YOUR_NEW_API_ENDPOINT").subscribe(data => {
 this.tableData = data;
 this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
 dtInstance.clear(); // Clear existing table data
 dtInstance.rows.add(this.tableData); // Add new data
 dtInstance.draw(); // Redraw the table
 });
 });
 }
 ngOnDestroy(): void {
 this.dtTrigger.unsubscribe();
 }
}