Angular Datatables - reload data












0















I use angular 6 with angular-datatables.



I try to define a "rerender" button in order to reload data like this exemple :



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



My datatable is more complex than the one described in the exemple and I get an issue with individual columns filters use:



This is my table before rerender action with filters use, all works fine:
enter image description here



But when I use these filters after data are reloaded, this is the result :
My non-visible column is now visible and page info are not updated..



enter image description here



Here is my TS file :



// Lifecycle hook that is called after a component's view has been fully initialized
ngAfterViewInit() {
console.log('ContactsComponent - ngAfterViewInit()');
this.dtTrigger.next();
this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
// console.log(dtInstance);
// console.log(dtInstance.data());
dtInstance.columns().every(function () {
const that = this;
$('input', this.footer()).on('keyup change', function () {
if (that.search() !== this['value']) {
that.search(this['value'])
.draw();
}
});
});
});

}
ngOnDestroy(): void {
console.log('ngDestroy');
// Do not forget to unsubscribe the event
this.dtTrigger.unsubscribe();
}
rerender(): void {
this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
dtInstance.columns().every(function () {
$('input', this.footer()).val('').change();
});
// Destroy the table first
dtInstance.destroy();
// Call the dtTrigger to rerender again
this.dtTrigger.next();
});
}


Here is my dtOptons config :



this.dtOptions = {
pagingType: 'full_numbers',
// displayLength: 10,
// serverSide: true, // si true, execute l'appel ajax, puis l'exécute à chaque utilisation d'un des filtres
// processing: true,
ajax: (dataTablesParameters: any, callback) => {
console.log('ContactsComponent - call Ajax()');
that.selectedList = ;
that.http.get<ApiResponse>('/api/contacts')
.subscribe(resp => {
that.contactList = resp.content;
that.loading = false;
callback({
data: that.contactList
});
},
error => {
console.log('authService.login error' + error);
console.log('error status : ' + error.status);
this.myJarviaServices.showNotification('top', 'center', error,
'danger', 1000);
this.alertService.error(error);
});
},
// deferRender: true,
columns: [
{
// title: 'Selection',
data: null },
{
// title: 'Identifiant',
data: 'identifiant' } ,
{
// title: 'Nom',
data: 'nom' },
{
// title: 'Prénom',
data: 'prenom' }
,
{
// title: 'Action',
data: null },
{
// title: 'Action',
data: 'idaicontact'}
],
columnDefs: [
{
orderable: false,
// className: 'my_class', // classname définit une checkbox par dessus une case vide [object Object] (data: null)
targets: [0],
render: function(data, type, full, meta) {
return'<input type="checkbox" class="unique-class mat-checkbox mat-accent mat-checkbox-anim-checked-unchecked ' +
'mat-checkbox-inner-container mat-checkbox-inner-container-no-side-margin">';
}
},
{
targets: [4],
visible: true,
data: 'action',
render: function(data, type, full, meta) {
return '<a class="btn btn-link btn-success btn-just-icon btn-edit" title="Editer">' +
'<i class="material-icons">create</i></a>' +
'<a class="btn btn-link btn-danger btn-just-icon btn-remove" title="Supprimer">' +
'<i class="material-icons">delete</i></a>' +
'<a class="btn btn-link btn-info btn-just-icon btn-read" title="Consulter">' +
'<i class="material-icons">visibility</i></a>'
}
},
{
targets: [5],
visible: false
}
],
rowCallback: (row: Node, data: any | Object, index: number) => {
const self = this;
// Unbind first in order to avoid any duplicate handler
// (see https://github.com/l-lin/angular-datatables/issues/87)
// $('td:first-child', row).unbind('click');
// $('td:first-child', row).bind('click', () => {
const elt = $('td', row).find('[type="checkbox"]');
if (elt) {
elt.unbind('click');
elt.bind('click', () => {
if (elt[0].checked) {
that.selectedList.push(data as Contact)
} else {
const itemIndex = this.selectedList.indexOf(data as Contact);
that.selectedList.splice(itemIndex, 1);
}
console.log(that.selectedList.length + ' éléments sélectionés');
this.selectedList.forEach((item) => {
console.log(item)
})
});
}
const eltedit = $('td', row).find('a.btn-edit');
if (eltedit) {
eltedit.unbind('click');
eltedit.bind('click', () => {
console.log(data);
this.crudContact(data, 2);
});
}
const eltrem = $('td', row).find('a.btn-remove');
if (eltrem) {
eltrem.unbind('click');
eltrem.bind('click', () => {
this.crudContact(data, 4);
});
}
const eltread = $('td', row).find('a.btn-read');
if (eltread) {
eltread.unbind('click');
eltread.bind('click', () => {
this.crudContact(data, 5);
});
}
return row;
},
lengthMenu: [[5, 10, 25, 50, -1], [5, 10, 25, 50, 'Tous']],
responsive: true,
language: {
lengthMenu: 'Afficher _MENU_ enregistrements par page',
zeroRecords: 'Aucun contact disponible',
info: '_START_ à _END_ sur un total de _TOTAL_ enregistrements',
// info: ' Page _PAGE_ sur _PAGES_',
infoEmpty: 'Aucun contact disponible',
infoFiltered: '(filtré(s) sur _MAX_ enregistrements)',
paginate: {
first: 'Premier',
last: 'dernier',
next: 'Suivant',
previous: 'Precedent'
},
search: '_INPUT_',
searchPlaceholder: 'Recherche',

},
order: [[1, 'desc']],
// Declare the use of the extension in the dom parameter
dom: 'Blfrtip',
stateSave: true,
buttons: [
{
extend: 'print',
className: 'btn btn-info btn-round btn-fab btn-fab-mini',
text: '<i class="material-icons" title="Imprimer">print</i>',
exportOptions: {
columns: [1, 2, 3]
}
},
{
extend: 'pdfHtml5',
className: 'btn btn-danger btn-round btn-fab btn-fab-mini',
text: '<i class="material-icons" title="Exporter au format pdf">save</i>',
exportOptions: {
columns: [1, 2, 3]
}
},
{
extend: 'excel',
className: 'btn btn-success btn-round btn-fab btn-fab-mini',
text: '<i class="material-icons" title="Exporter au format xls">save</i>',
exportOptions: {
columns: [1, 2, 3]
}
},
{
text: '<i class="material-icons" title="Supprimer">delete</i>',
className: 'btn btn-danger btn-round btn-fab btn-fab-mini',
action: function (e, dt, node, config) {
that.checkSelect(dt);
}
},
// {
// text: '<i class="material-icons" title="Actualiser">replay</i>',
// className: 'btn btn-primary btn-round btn-fab btn-fab-mini',
// action: function (e, dt, node, config) {
// that.refresh();
// }
// },
{
text: '<i class="material-icons" title="Nouveau">add</i>',
className: 'btn btn-warning btn-round btn-fab btn-fab-mini',
action: function (e, dt, node, config) {
that.crudContact(null, 1);
}
}
]
};


Here is my HTML file :



<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%">
<!--<table #dataTable class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%">-->
<tfoot>
<tr>
<th>Sélection</th>
<!--<th>id</th>-->
<th><input type="text" placeholder="Recherche Identifiant" name="search-identifiant"/></th>
<th><input type="text" placeholder="Recherche Nom" name="search-nom"/></th>
<th><input type="text" placeholder="Recherche prénom" name="search-prenom"/></th>
<th>Action</th>
<th>#</th>
</tr>
</tfoot>
<thead>
<tr>
<th style="width: 1%">
<mat-checkbox (change)="$event ? masterToggle() : null"
[checked]="selection.hasValue() && isAllSelected(contactList.length)">
</mat-checkbox>
</th>
<th><b>Identifiant</b></th>
<th><b>Nom</b></th>
<th><b>Prenom</b></th>
<th><b>Action</b></th>
<th><b>#</b></th>
</tr>
</thead>
</table>









share|improve this question

























  • Same issue, did you figure it out?

    – Nasri Yatim
    Dec 17 '18 at 8:39











  • Yes, I post the answer

    – anakin59490
    Dec 17 '18 at 14:23
















0















I use angular 6 with angular-datatables.



I try to define a "rerender" button in order to reload data like this exemple :



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



My datatable is more complex than the one described in the exemple and I get an issue with individual columns filters use:



This is my table before rerender action with filters use, all works fine:
enter image description here



But when I use these filters after data are reloaded, this is the result :
My non-visible column is now visible and page info are not updated..



enter image description here



Here is my TS file :



// Lifecycle hook that is called after a component's view has been fully initialized
ngAfterViewInit() {
console.log('ContactsComponent - ngAfterViewInit()');
this.dtTrigger.next();
this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
// console.log(dtInstance);
// console.log(dtInstance.data());
dtInstance.columns().every(function () {
const that = this;
$('input', this.footer()).on('keyup change', function () {
if (that.search() !== this['value']) {
that.search(this['value'])
.draw();
}
});
});
});

}
ngOnDestroy(): void {
console.log('ngDestroy');
// Do not forget to unsubscribe the event
this.dtTrigger.unsubscribe();
}
rerender(): void {
this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
dtInstance.columns().every(function () {
$('input', this.footer()).val('').change();
});
// Destroy the table first
dtInstance.destroy();
// Call the dtTrigger to rerender again
this.dtTrigger.next();
});
}


Here is my dtOptons config :



this.dtOptions = {
pagingType: 'full_numbers',
// displayLength: 10,
// serverSide: true, // si true, execute l'appel ajax, puis l'exécute à chaque utilisation d'un des filtres
// processing: true,
ajax: (dataTablesParameters: any, callback) => {
console.log('ContactsComponent - call Ajax()');
that.selectedList = ;
that.http.get<ApiResponse>('/api/contacts')
.subscribe(resp => {
that.contactList = resp.content;
that.loading = false;
callback({
data: that.contactList
});
},
error => {
console.log('authService.login error' + error);
console.log('error status : ' + error.status);
this.myJarviaServices.showNotification('top', 'center', error,
'danger', 1000);
this.alertService.error(error);
});
},
// deferRender: true,
columns: [
{
// title: 'Selection',
data: null },
{
// title: 'Identifiant',
data: 'identifiant' } ,
{
// title: 'Nom',
data: 'nom' },
{
// title: 'Prénom',
data: 'prenom' }
,
{
// title: 'Action',
data: null },
{
// title: 'Action',
data: 'idaicontact'}
],
columnDefs: [
{
orderable: false,
// className: 'my_class', // classname définit une checkbox par dessus une case vide [object Object] (data: null)
targets: [0],
render: function(data, type, full, meta) {
return'<input type="checkbox" class="unique-class mat-checkbox mat-accent mat-checkbox-anim-checked-unchecked ' +
'mat-checkbox-inner-container mat-checkbox-inner-container-no-side-margin">';
}
},
{
targets: [4],
visible: true,
data: 'action',
render: function(data, type, full, meta) {
return '<a class="btn btn-link btn-success btn-just-icon btn-edit" title="Editer">' +
'<i class="material-icons">create</i></a>' +
'<a class="btn btn-link btn-danger btn-just-icon btn-remove" title="Supprimer">' +
'<i class="material-icons">delete</i></a>' +
'<a class="btn btn-link btn-info btn-just-icon btn-read" title="Consulter">' +
'<i class="material-icons">visibility</i></a>'
}
},
{
targets: [5],
visible: false
}
],
rowCallback: (row: Node, data: any | Object, index: number) => {
const self = this;
// Unbind first in order to avoid any duplicate handler
// (see https://github.com/l-lin/angular-datatables/issues/87)
// $('td:first-child', row).unbind('click');
// $('td:first-child', row).bind('click', () => {
const elt = $('td', row).find('[type="checkbox"]');
if (elt) {
elt.unbind('click');
elt.bind('click', () => {
if (elt[0].checked) {
that.selectedList.push(data as Contact)
} else {
const itemIndex = this.selectedList.indexOf(data as Contact);
that.selectedList.splice(itemIndex, 1);
}
console.log(that.selectedList.length + ' éléments sélectionés');
this.selectedList.forEach((item) => {
console.log(item)
})
});
}
const eltedit = $('td', row).find('a.btn-edit');
if (eltedit) {
eltedit.unbind('click');
eltedit.bind('click', () => {
console.log(data);
this.crudContact(data, 2);
});
}
const eltrem = $('td', row).find('a.btn-remove');
if (eltrem) {
eltrem.unbind('click');
eltrem.bind('click', () => {
this.crudContact(data, 4);
});
}
const eltread = $('td', row).find('a.btn-read');
if (eltread) {
eltread.unbind('click');
eltread.bind('click', () => {
this.crudContact(data, 5);
});
}
return row;
},
lengthMenu: [[5, 10, 25, 50, -1], [5, 10, 25, 50, 'Tous']],
responsive: true,
language: {
lengthMenu: 'Afficher _MENU_ enregistrements par page',
zeroRecords: 'Aucun contact disponible',
info: '_START_ à _END_ sur un total de _TOTAL_ enregistrements',
// info: ' Page _PAGE_ sur _PAGES_',
infoEmpty: 'Aucun contact disponible',
infoFiltered: '(filtré(s) sur _MAX_ enregistrements)',
paginate: {
first: 'Premier',
last: 'dernier',
next: 'Suivant',
previous: 'Precedent'
},
search: '_INPUT_',
searchPlaceholder: 'Recherche',

},
order: [[1, 'desc']],
// Declare the use of the extension in the dom parameter
dom: 'Blfrtip',
stateSave: true,
buttons: [
{
extend: 'print',
className: 'btn btn-info btn-round btn-fab btn-fab-mini',
text: '<i class="material-icons" title="Imprimer">print</i>',
exportOptions: {
columns: [1, 2, 3]
}
},
{
extend: 'pdfHtml5',
className: 'btn btn-danger btn-round btn-fab btn-fab-mini',
text: '<i class="material-icons" title="Exporter au format pdf">save</i>',
exportOptions: {
columns: [1, 2, 3]
}
},
{
extend: 'excel',
className: 'btn btn-success btn-round btn-fab btn-fab-mini',
text: '<i class="material-icons" title="Exporter au format xls">save</i>',
exportOptions: {
columns: [1, 2, 3]
}
},
{
text: '<i class="material-icons" title="Supprimer">delete</i>',
className: 'btn btn-danger btn-round btn-fab btn-fab-mini',
action: function (e, dt, node, config) {
that.checkSelect(dt);
}
},
// {
// text: '<i class="material-icons" title="Actualiser">replay</i>',
// className: 'btn btn-primary btn-round btn-fab btn-fab-mini',
// action: function (e, dt, node, config) {
// that.refresh();
// }
// },
{
text: '<i class="material-icons" title="Nouveau">add</i>',
className: 'btn btn-warning btn-round btn-fab btn-fab-mini',
action: function (e, dt, node, config) {
that.crudContact(null, 1);
}
}
]
};


Here is my HTML file :



<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%">
<!--<table #dataTable class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%">-->
<tfoot>
<tr>
<th>Sélection</th>
<!--<th>id</th>-->
<th><input type="text" placeholder="Recherche Identifiant" name="search-identifiant"/></th>
<th><input type="text" placeholder="Recherche Nom" name="search-nom"/></th>
<th><input type="text" placeholder="Recherche prénom" name="search-prenom"/></th>
<th>Action</th>
<th>#</th>
</tr>
</tfoot>
<thead>
<tr>
<th style="width: 1%">
<mat-checkbox (change)="$event ? masterToggle() : null"
[checked]="selection.hasValue() && isAllSelected(contactList.length)">
</mat-checkbox>
</th>
<th><b>Identifiant</b></th>
<th><b>Nom</b></th>
<th><b>Prenom</b></th>
<th><b>Action</b></th>
<th><b>#</b></th>
</tr>
</thead>
</table>









share|improve this question

























  • Same issue, did you figure it out?

    – Nasri Yatim
    Dec 17 '18 at 8:39











  • Yes, I post the answer

    – anakin59490
    Dec 17 '18 at 14:23














0












0








0








I use angular 6 with angular-datatables.



I try to define a "rerender" button in order to reload data like this exemple :



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



My datatable is more complex than the one described in the exemple and I get an issue with individual columns filters use:



This is my table before rerender action with filters use, all works fine:
enter image description here



But when I use these filters after data are reloaded, this is the result :
My non-visible column is now visible and page info are not updated..



enter image description here



Here is my TS file :



// Lifecycle hook that is called after a component's view has been fully initialized
ngAfterViewInit() {
console.log('ContactsComponent - ngAfterViewInit()');
this.dtTrigger.next();
this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
// console.log(dtInstance);
// console.log(dtInstance.data());
dtInstance.columns().every(function () {
const that = this;
$('input', this.footer()).on('keyup change', function () {
if (that.search() !== this['value']) {
that.search(this['value'])
.draw();
}
});
});
});

}
ngOnDestroy(): void {
console.log('ngDestroy');
// Do not forget to unsubscribe the event
this.dtTrigger.unsubscribe();
}
rerender(): void {
this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
dtInstance.columns().every(function () {
$('input', this.footer()).val('').change();
});
// Destroy the table first
dtInstance.destroy();
// Call the dtTrigger to rerender again
this.dtTrigger.next();
});
}


Here is my dtOptons config :



this.dtOptions = {
pagingType: 'full_numbers',
// displayLength: 10,
// serverSide: true, // si true, execute l'appel ajax, puis l'exécute à chaque utilisation d'un des filtres
// processing: true,
ajax: (dataTablesParameters: any, callback) => {
console.log('ContactsComponent - call Ajax()');
that.selectedList = ;
that.http.get<ApiResponse>('/api/contacts')
.subscribe(resp => {
that.contactList = resp.content;
that.loading = false;
callback({
data: that.contactList
});
},
error => {
console.log('authService.login error' + error);
console.log('error status : ' + error.status);
this.myJarviaServices.showNotification('top', 'center', error,
'danger', 1000);
this.alertService.error(error);
});
},
// deferRender: true,
columns: [
{
// title: 'Selection',
data: null },
{
// title: 'Identifiant',
data: 'identifiant' } ,
{
// title: 'Nom',
data: 'nom' },
{
// title: 'Prénom',
data: 'prenom' }
,
{
// title: 'Action',
data: null },
{
// title: 'Action',
data: 'idaicontact'}
],
columnDefs: [
{
orderable: false,
// className: 'my_class', // classname définit une checkbox par dessus une case vide [object Object] (data: null)
targets: [0],
render: function(data, type, full, meta) {
return'<input type="checkbox" class="unique-class mat-checkbox mat-accent mat-checkbox-anim-checked-unchecked ' +
'mat-checkbox-inner-container mat-checkbox-inner-container-no-side-margin">';
}
},
{
targets: [4],
visible: true,
data: 'action',
render: function(data, type, full, meta) {
return '<a class="btn btn-link btn-success btn-just-icon btn-edit" title="Editer">' +
'<i class="material-icons">create</i></a>' +
'<a class="btn btn-link btn-danger btn-just-icon btn-remove" title="Supprimer">' +
'<i class="material-icons">delete</i></a>' +
'<a class="btn btn-link btn-info btn-just-icon btn-read" title="Consulter">' +
'<i class="material-icons">visibility</i></a>'
}
},
{
targets: [5],
visible: false
}
],
rowCallback: (row: Node, data: any | Object, index: number) => {
const self = this;
// Unbind first in order to avoid any duplicate handler
// (see https://github.com/l-lin/angular-datatables/issues/87)
// $('td:first-child', row).unbind('click');
// $('td:first-child', row).bind('click', () => {
const elt = $('td', row).find('[type="checkbox"]');
if (elt) {
elt.unbind('click');
elt.bind('click', () => {
if (elt[0].checked) {
that.selectedList.push(data as Contact)
} else {
const itemIndex = this.selectedList.indexOf(data as Contact);
that.selectedList.splice(itemIndex, 1);
}
console.log(that.selectedList.length + ' éléments sélectionés');
this.selectedList.forEach((item) => {
console.log(item)
})
});
}
const eltedit = $('td', row).find('a.btn-edit');
if (eltedit) {
eltedit.unbind('click');
eltedit.bind('click', () => {
console.log(data);
this.crudContact(data, 2);
});
}
const eltrem = $('td', row).find('a.btn-remove');
if (eltrem) {
eltrem.unbind('click');
eltrem.bind('click', () => {
this.crudContact(data, 4);
});
}
const eltread = $('td', row).find('a.btn-read');
if (eltread) {
eltread.unbind('click');
eltread.bind('click', () => {
this.crudContact(data, 5);
});
}
return row;
},
lengthMenu: [[5, 10, 25, 50, -1], [5, 10, 25, 50, 'Tous']],
responsive: true,
language: {
lengthMenu: 'Afficher _MENU_ enregistrements par page',
zeroRecords: 'Aucun contact disponible',
info: '_START_ à _END_ sur un total de _TOTAL_ enregistrements',
// info: ' Page _PAGE_ sur _PAGES_',
infoEmpty: 'Aucun contact disponible',
infoFiltered: '(filtré(s) sur _MAX_ enregistrements)',
paginate: {
first: 'Premier',
last: 'dernier',
next: 'Suivant',
previous: 'Precedent'
},
search: '_INPUT_',
searchPlaceholder: 'Recherche',

},
order: [[1, 'desc']],
// Declare the use of the extension in the dom parameter
dom: 'Blfrtip',
stateSave: true,
buttons: [
{
extend: 'print',
className: 'btn btn-info btn-round btn-fab btn-fab-mini',
text: '<i class="material-icons" title="Imprimer">print</i>',
exportOptions: {
columns: [1, 2, 3]
}
},
{
extend: 'pdfHtml5',
className: 'btn btn-danger btn-round btn-fab btn-fab-mini',
text: '<i class="material-icons" title="Exporter au format pdf">save</i>',
exportOptions: {
columns: [1, 2, 3]
}
},
{
extend: 'excel',
className: 'btn btn-success btn-round btn-fab btn-fab-mini',
text: '<i class="material-icons" title="Exporter au format xls">save</i>',
exportOptions: {
columns: [1, 2, 3]
}
},
{
text: '<i class="material-icons" title="Supprimer">delete</i>',
className: 'btn btn-danger btn-round btn-fab btn-fab-mini',
action: function (e, dt, node, config) {
that.checkSelect(dt);
}
},
// {
// text: '<i class="material-icons" title="Actualiser">replay</i>',
// className: 'btn btn-primary btn-round btn-fab btn-fab-mini',
// action: function (e, dt, node, config) {
// that.refresh();
// }
// },
{
text: '<i class="material-icons" title="Nouveau">add</i>',
className: 'btn btn-warning btn-round btn-fab btn-fab-mini',
action: function (e, dt, node, config) {
that.crudContact(null, 1);
}
}
]
};


Here is my HTML file :



<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%">
<!--<table #dataTable class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%">-->
<tfoot>
<tr>
<th>Sélection</th>
<!--<th>id</th>-->
<th><input type="text" placeholder="Recherche Identifiant" name="search-identifiant"/></th>
<th><input type="text" placeholder="Recherche Nom" name="search-nom"/></th>
<th><input type="text" placeholder="Recherche prénom" name="search-prenom"/></th>
<th>Action</th>
<th>#</th>
</tr>
</tfoot>
<thead>
<tr>
<th style="width: 1%">
<mat-checkbox (change)="$event ? masterToggle() : null"
[checked]="selection.hasValue() && isAllSelected(contactList.length)">
</mat-checkbox>
</th>
<th><b>Identifiant</b></th>
<th><b>Nom</b></th>
<th><b>Prenom</b></th>
<th><b>Action</b></th>
<th><b>#</b></th>
</tr>
</thead>
</table>









share|improve this question
















I use angular 6 with angular-datatables.



I try to define a "rerender" button in order to reload data like this exemple :



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



My datatable is more complex than the one described in the exemple and I get an issue with individual columns filters use:



This is my table before rerender action with filters use, all works fine:
enter image description here



But when I use these filters after data are reloaded, this is the result :
My non-visible column is now visible and page info are not updated..



enter image description here



Here is my TS file :



// Lifecycle hook that is called after a component's view has been fully initialized
ngAfterViewInit() {
console.log('ContactsComponent - ngAfterViewInit()');
this.dtTrigger.next();
this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
// console.log(dtInstance);
// console.log(dtInstance.data());
dtInstance.columns().every(function () {
const that = this;
$('input', this.footer()).on('keyup change', function () {
if (that.search() !== this['value']) {
that.search(this['value'])
.draw();
}
});
});
});

}
ngOnDestroy(): void {
console.log('ngDestroy');
// Do not forget to unsubscribe the event
this.dtTrigger.unsubscribe();
}
rerender(): void {
this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
dtInstance.columns().every(function () {
$('input', this.footer()).val('').change();
});
// Destroy the table first
dtInstance.destroy();
// Call the dtTrigger to rerender again
this.dtTrigger.next();
});
}


Here is my dtOptons config :



this.dtOptions = {
pagingType: 'full_numbers',
// displayLength: 10,
// serverSide: true, // si true, execute l'appel ajax, puis l'exécute à chaque utilisation d'un des filtres
// processing: true,
ajax: (dataTablesParameters: any, callback) => {
console.log('ContactsComponent - call Ajax()');
that.selectedList = ;
that.http.get<ApiResponse>('/api/contacts')
.subscribe(resp => {
that.contactList = resp.content;
that.loading = false;
callback({
data: that.contactList
});
},
error => {
console.log('authService.login error' + error);
console.log('error status : ' + error.status);
this.myJarviaServices.showNotification('top', 'center', error,
'danger', 1000);
this.alertService.error(error);
});
},
// deferRender: true,
columns: [
{
// title: 'Selection',
data: null },
{
// title: 'Identifiant',
data: 'identifiant' } ,
{
// title: 'Nom',
data: 'nom' },
{
// title: 'Prénom',
data: 'prenom' }
,
{
// title: 'Action',
data: null },
{
// title: 'Action',
data: 'idaicontact'}
],
columnDefs: [
{
orderable: false,
// className: 'my_class', // classname définit une checkbox par dessus une case vide [object Object] (data: null)
targets: [0],
render: function(data, type, full, meta) {
return'<input type="checkbox" class="unique-class mat-checkbox mat-accent mat-checkbox-anim-checked-unchecked ' +
'mat-checkbox-inner-container mat-checkbox-inner-container-no-side-margin">';
}
},
{
targets: [4],
visible: true,
data: 'action',
render: function(data, type, full, meta) {
return '<a class="btn btn-link btn-success btn-just-icon btn-edit" title="Editer">' +
'<i class="material-icons">create</i></a>' +
'<a class="btn btn-link btn-danger btn-just-icon btn-remove" title="Supprimer">' +
'<i class="material-icons">delete</i></a>' +
'<a class="btn btn-link btn-info btn-just-icon btn-read" title="Consulter">' +
'<i class="material-icons">visibility</i></a>'
}
},
{
targets: [5],
visible: false
}
],
rowCallback: (row: Node, data: any | Object, index: number) => {
const self = this;
// Unbind first in order to avoid any duplicate handler
// (see https://github.com/l-lin/angular-datatables/issues/87)
// $('td:first-child', row).unbind('click');
// $('td:first-child', row).bind('click', () => {
const elt = $('td', row).find('[type="checkbox"]');
if (elt) {
elt.unbind('click');
elt.bind('click', () => {
if (elt[0].checked) {
that.selectedList.push(data as Contact)
} else {
const itemIndex = this.selectedList.indexOf(data as Contact);
that.selectedList.splice(itemIndex, 1);
}
console.log(that.selectedList.length + ' éléments sélectionés');
this.selectedList.forEach((item) => {
console.log(item)
})
});
}
const eltedit = $('td', row).find('a.btn-edit');
if (eltedit) {
eltedit.unbind('click');
eltedit.bind('click', () => {
console.log(data);
this.crudContact(data, 2);
});
}
const eltrem = $('td', row).find('a.btn-remove');
if (eltrem) {
eltrem.unbind('click');
eltrem.bind('click', () => {
this.crudContact(data, 4);
});
}
const eltread = $('td', row).find('a.btn-read');
if (eltread) {
eltread.unbind('click');
eltread.bind('click', () => {
this.crudContact(data, 5);
});
}
return row;
},
lengthMenu: [[5, 10, 25, 50, -1], [5, 10, 25, 50, 'Tous']],
responsive: true,
language: {
lengthMenu: 'Afficher _MENU_ enregistrements par page',
zeroRecords: 'Aucun contact disponible',
info: '_START_ à _END_ sur un total de _TOTAL_ enregistrements',
// info: ' Page _PAGE_ sur _PAGES_',
infoEmpty: 'Aucun contact disponible',
infoFiltered: '(filtré(s) sur _MAX_ enregistrements)',
paginate: {
first: 'Premier',
last: 'dernier',
next: 'Suivant',
previous: 'Precedent'
},
search: '_INPUT_',
searchPlaceholder: 'Recherche',

},
order: [[1, 'desc']],
// Declare the use of the extension in the dom parameter
dom: 'Blfrtip',
stateSave: true,
buttons: [
{
extend: 'print',
className: 'btn btn-info btn-round btn-fab btn-fab-mini',
text: '<i class="material-icons" title="Imprimer">print</i>',
exportOptions: {
columns: [1, 2, 3]
}
},
{
extend: 'pdfHtml5',
className: 'btn btn-danger btn-round btn-fab btn-fab-mini',
text: '<i class="material-icons" title="Exporter au format pdf">save</i>',
exportOptions: {
columns: [1, 2, 3]
}
},
{
extend: 'excel',
className: 'btn btn-success btn-round btn-fab btn-fab-mini',
text: '<i class="material-icons" title="Exporter au format xls">save</i>',
exportOptions: {
columns: [1, 2, 3]
}
},
{
text: '<i class="material-icons" title="Supprimer">delete</i>',
className: 'btn btn-danger btn-round btn-fab btn-fab-mini',
action: function (e, dt, node, config) {
that.checkSelect(dt);
}
},
// {
// text: '<i class="material-icons" title="Actualiser">replay</i>',
// className: 'btn btn-primary btn-round btn-fab btn-fab-mini',
// action: function (e, dt, node, config) {
// that.refresh();
// }
// },
{
text: '<i class="material-icons" title="Nouveau">add</i>',
className: 'btn btn-warning btn-round btn-fab btn-fab-mini',
action: function (e, dt, node, config) {
that.crudContact(null, 1);
}
}
]
};


Here is my HTML file :



<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%">
<!--<table #dataTable class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%">-->
<tfoot>
<tr>
<th>Sélection</th>
<!--<th>id</th>-->
<th><input type="text" placeholder="Recherche Identifiant" name="search-identifiant"/></th>
<th><input type="text" placeholder="Recherche Nom" name="search-nom"/></th>
<th><input type="text" placeholder="Recherche prénom" name="search-prenom"/></th>
<th>Action</th>
<th>#</th>
</tr>
</tfoot>
<thead>
<tr>
<th style="width: 1%">
<mat-checkbox (change)="$event ? masterToggle() : null"
[checked]="selection.hasValue() && isAllSelected(contactList.length)">
</mat-checkbox>
</th>
<th><b>Identifiant</b></th>
<th><b>Nom</b></th>
<th><b>Prenom</b></th>
<th><b>Action</b></th>
<th><b>#</b></th>
</tr>
</thead>
</table>






angular datatables angular6 angular-datatables






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 13:51









rrd

2,90731322




2,90731322










asked Nov 14 '18 at 13:48









anakin59490anakin59490

15614




15614













  • Same issue, did you figure it out?

    – Nasri Yatim
    Dec 17 '18 at 8:39











  • Yes, I post the answer

    – anakin59490
    Dec 17 '18 at 14:23



















  • Same issue, did you figure it out?

    – Nasri Yatim
    Dec 17 '18 at 8:39











  • Yes, I post the answer

    – anakin59490
    Dec 17 '18 at 14:23

















Same issue, did you figure it out?

– Nasri Yatim
Dec 17 '18 at 8:39





Same issue, did you figure it out?

– Nasri Yatim
Dec 17 '18 at 8:39













Yes, I post the answer

– anakin59490
Dec 17 '18 at 14:23





Yes, I post the answer

– anakin59490
Dec 17 '18 at 14:23












1 Answer
1






active

oldest

votes


















1














Found !



Firstly : Move filter code in method, example :



afterView() {
this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
// console.log(dtInstance);
// console.log(dtInstance.data());
dtInstance.columns().every(function () {
const that = this;
$('input', this.footer()).on('keyup change', function () {
if (that.search() !== this['value']) {
that.search(this['value'])
.draw();
}
});
});
// dtInstance.on('search.dt', function() {
// // Do you stuff
// console.log('search: ' + dtInstance.search());
// });
});
}


So when filters are applied, this method is called as following :



 ngAfterViewInit() {
console.log('ContactsComponent - ngAfterViewInit()');
this.dtTrigger.next();
this.afterView();

}


When a filter is applied and that we call rerender method, we must recall this method after loading data :



 ajax: (dataTablesParameters: any, callback) => {
console.log('ContactsComponent - call Ajax()');
that.selectedList = ;
that.http.get<ApiResponse>('/api/contacts')
.subscribe(resp => {
that.contactList = resp.content;
that.loading = false;
// on charge la table telle qu'elle était avant le reloading (filtres éventuels)
this.afterView();
callback({
data: that.contactList
});
},
error => {
console.log('authService.login error' + error);
console.log('error status : ' + error.status);
this.alertService.error(error);
this.myJarviaServices.error(error);
});
},


And it works fine !






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53301764%2fangular-datatables-reload-data%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Found !



    Firstly : Move filter code in method, example :



    afterView() {
    this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
    // console.log(dtInstance);
    // console.log(dtInstance.data());
    dtInstance.columns().every(function () {
    const that = this;
    $('input', this.footer()).on('keyup change', function () {
    if (that.search() !== this['value']) {
    that.search(this['value'])
    .draw();
    }
    });
    });
    // dtInstance.on('search.dt', function() {
    // // Do you stuff
    // console.log('search: ' + dtInstance.search());
    // });
    });
    }


    So when filters are applied, this method is called as following :



     ngAfterViewInit() {
    console.log('ContactsComponent - ngAfterViewInit()');
    this.dtTrigger.next();
    this.afterView();

    }


    When a filter is applied and that we call rerender method, we must recall this method after loading data :



     ajax: (dataTablesParameters: any, callback) => {
    console.log('ContactsComponent - call Ajax()');
    that.selectedList = ;
    that.http.get<ApiResponse>('/api/contacts')
    .subscribe(resp => {
    that.contactList = resp.content;
    that.loading = false;
    // on charge la table telle qu'elle était avant le reloading (filtres éventuels)
    this.afterView();
    callback({
    data: that.contactList
    });
    },
    error => {
    console.log('authService.login error' + error);
    console.log('error status : ' + error.status);
    this.alertService.error(error);
    this.myJarviaServices.error(error);
    });
    },


    And it works fine !






    share|improve this answer




























      1














      Found !



      Firstly : Move filter code in method, example :



      afterView() {
      this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
      // console.log(dtInstance);
      // console.log(dtInstance.data());
      dtInstance.columns().every(function () {
      const that = this;
      $('input', this.footer()).on('keyup change', function () {
      if (that.search() !== this['value']) {
      that.search(this['value'])
      .draw();
      }
      });
      });
      // dtInstance.on('search.dt', function() {
      // // Do you stuff
      // console.log('search: ' + dtInstance.search());
      // });
      });
      }


      So when filters are applied, this method is called as following :



       ngAfterViewInit() {
      console.log('ContactsComponent - ngAfterViewInit()');
      this.dtTrigger.next();
      this.afterView();

      }


      When a filter is applied and that we call rerender method, we must recall this method after loading data :



       ajax: (dataTablesParameters: any, callback) => {
      console.log('ContactsComponent - call Ajax()');
      that.selectedList = ;
      that.http.get<ApiResponse>('/api/contacts')
      .subscribe(resp => {
      that.contactList = resp.content;
      that.loading = false;
      // on charge la table telle qu'elle était avant le reloading (filtres éventuels)
      this.afterView();
      callback({
      data: that.contactList
      });
      },
      error => {
      console.log('authService.login error' + error);
      console.log('error status : ' + error.status);
      this.alertService.error(error);
      this.myJarviaServices.error(error);
      });
      },


      And it works fine !






      share|improve this answer


























        1












        1








        1







        Found !



        Firstly : Move filter code in method, example :



        afterView() {
        this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
        // console.log(dtInstance);
        // console.log(dtInstance.data());
        dtInstance.columns().every(function () {
        const that = this;
        $('input', this.footer()).on('keyup change', function () {
        if (that.search() !== this['value']) {
        that.search(this['value'])
        .draw();
        }
        });
        });
        // dtInstance.on('search.dt', function() {
        // // Do you stuff
        // console.log('search: ' + dtInstance.search());
        // });
        });
        }


        So when filters are applied, this method is called as following :



         ngAfterViewInit() {
        console.log('ContactsComponent - ngAfterViewInit()');
        this.dtTrigger.next();
        this.afterView();

        }


        When a filter is applied and that we call rerender method, we must recall this method after loading data :



         ajax: (dataTablesParameters: any, callback) => {
        console.log('ContactsComponent - call Ajax()');
        that.selectedList = ;
        that.http.get<ApiResponse>('/api/contacts')
        .subscribe(resp => {
        that.contactList = resp.content;
        that.loading = false;
        // on charge la table telle qu'elle était avant le reloading (filtres éventuels)
        this.afterView();
        callback({
        data: that.contactList
        });
        },
        error => {
        console.log('authService.login error' + error);
        console.log('error status : ' + error.status);
        this.alertService.error(error);
        this.myJarviaServices.error(error);
        });
        },


        And it works fine !






        share|improve this answer













        Found !



        Firstly : Move filter code in method, example :



        afterView() {
        this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
        // console.log(dtInstance);
        // console.log(dtInstance.data());
        dtInstance.columns().every(function () {
        const that = this;
        $('input', this.footer()).on('keyup change', function () {
        if (that.search() !== this['value']) {
        that.search(this['value'])
        .draw();
        }
        });
        });
        // dtInstance.on('search.dt', function() {
        // // Do you stuff
        // console.log('search: ' + dtInstance.search());
        // });
        });
        }


        So when filters are applied, this method is called as following :



         ngAfterViewInit() {
        console.log('ContactsComponent - ngAfterViewInit()');
        this.dtTrigger.next();
        this.afterView();

        }


        When a filter is applied and that we call rerender method, we must recall this method after loading data :



         ajax: (dataTablesParameters: any, callback) => {
        console.log('ContactsComponent - call Ajax()');
        that.selectedList = ;
        that.http.get<ApiResponse>('/api/contacts')
        .subscribe(resp => {
        that.contactList = resp.content;
        that.loading = false;
        // on charge la table telle qu'elle était avant le reloading (filtres éventuels)
        this.afterView();
        callback({
        data: that.contactList
        });
        },
        error => {
        console.log('authService.login error' + error);
        console.log('error status : ' + error.status);
        this.alertService.error(error);
        this.myJarviaServices.error(error);
        });
        },


        And it works fine !







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 17 '18 at 14:21









        anakin59490anakin59490

        15614




        15614
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53301764%2fangular-datatables-reload-data%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Florida Star v. B. J. F.

            Danny Elfman

            Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues