This is an interesting case, Im achieving to get the current state of array of the columns when I use pure JS + jQuery but when trying to achieve the same thing in Angular 12 this won't work! Im reading the docs of Angular datatables also datatables.net but this won't work on the project!
Here is the code im trying to set up in Angular:
import { Component, OnInit, ViewChild } from '@angular/core';
declare var $:JQueryStatic;
@Component({
selector: 'app-mandant',
templateUrl: './mandant.component.html',
styleUrls: ['./mandant.component.scss']
})
export class MandantComponent implements OnInit {
dtOptions = {};
constructor() { }
ngOnInit(): void {
this.dtOptions = {
dom: 'Bfrtip',
bLengthChange: true,
searching: false,
table: "#dttable",
info: true,
buttons: [
'colvis',
'copy',
'print',
'excel',
{
text: 'Some button',
key: '1',
action: function (e: any, dt: any, node: any, config: any) {
alert('Button activated');
}
}
],
colReorder: {
enable: true,
order: [1, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
}
};
this.dtOptions.on('column-reorder.dt', function (e, settings, details) {
console.log("You just reordered the cols, here is your current state: ", this.dtOptions.order());
});
}
ngAfterViewInit(): void {
}
}
The achievement for me is this piece of code, if this code returns the current state of the array after each change on the columns, my concern is done:
this.dtOptions.on('column-reorder.dt', function (e, settings, details) {
console.log("You just reordered the cols, here is your current state: ", this.dtOptions.order());
});
I found the solution after few days, I was trying to load everything on ngViewInit(); but actualy I had to do that on ngAfterViewInit();:
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-mandant',
templateUrl: './mandant.component.html',
styleUrls: ['./mandant.component.scss']
})
export class MandantComponent implements OnInit, AfterViewInit {
@ViewChild('dataTable', { static: false }) table: any;
dtOptions: any;
constructor() { }
ngAfterViewInit(): void {
var cols: any = localStorage.getItem("mandanten") === null ? null : JSON.parse(localStorage.getItem("mandanten") || "[]");
this.dtOptions = {
dom: "Bfrtip",
"buttons": [
"colvis",
"copy",
"excel"
],
"colReorder": {
"enable": true,
"realtime": false,
"order": cols,
}
};
var table: any = $(this.table.nativeElement).DataTable(this.dtOptions);
table.on("column-reorder", function () {
localStorage.setItem("mandanten", JSON.stringify(table.colReorder.order()));
});
table.on( 'buttons-action', function ( e: any, buttonApi: any, dataTable: any, node: any, config: any ) {
console.log(buttonApi.columns());
} );
};
ngOnInit(): void { }
}