Reputation: 33
I fetch data from webservice in ngOnInit block and then i need to apply jquery data table plugin (this action i performed both in ngAfterViewInit and ngAfterContentInit). The problem is that jquery datatable plugin don't see data in the component table which was fetched in ngOnInit block. The only way I could implement this is setTimeout or setInterval (which stops execution if plugin instance created).
Is there any other method to perform task I try to ?
export class DataTable implements OnInit, AfterViewInit, AfterContentInit, AfterContentChecked {
public data = null;
public table = null;
constructor(public translate: TranslateService, public ngZone: NgZone) {
}
ngOnInit(): void {
this.translate.getData().subscribe((records) => {
this.data = records;
});
}
ngAfterViewInit(): void {
this.dataTableDynamicUpdater();
}
ngAfterContentInit() : void {
}
ngAfterContentChecked() {
}
dataTableDynamicUpdater() {
let self = this;
let interval = setInterval(() => {
if(self.data) {
self.instantiateDataTable();
clearInterval(interval);
}
}, 200);
}
instantiateDataTable() {
let _FILTER_PLACEHOLDER_ = this.translate.instant('APP_DATATABLE_PLACEHOLDER_TYPE_TO_FILTER');
let _FILTER_LABEL_ = this.translate.instant('APP_DATATABLE_LABEL_FILTER');
let _SHOW_LABEL_ = this.translate.instant('APP_DATATABLE_LABEL_SHOW');
$.extend($.fn.dataTable.defaults, {
autoWidth: false,
dom: '<"datatable-header"fBl><"datatable-scroll-wrap"t><"datatable-footer"ip>',
language: {
search: '<span>_FILTER_LABEL_</span> _INPUT_',
lengthMenu: '<span>_SHOW_LABEL_</span> _MENU_',
paginate: { 'first': 'First', 'last': 'Last', 'next': '→', 'previous': '←' }
}
});
// Column selectors
let table = $('.table').DataTable({
buttons: {
buttons: [
{
extend: 'excelHtml5',
className: 'btn btn-default',
exportOptions: {
columns: ':visible'
}
}
]
}
});
// Add placeholder to the datatable filter option
$('.dataTables_filter input[type=search]').attr('placeholder', _FILTER_PLACEHOLDER_);
// Enable Select2 select for the length option
$('.dataTables_length select').select2({
minimumResultsForSearch: Infinity,
width: 'auto'
});
return table;
}
}
Upvotes: 0
Views: 63
Reputation: 9402
Try doing it after the data was fetched
ngOnInit(): void {
let self = this;
this.translate.getData().subscribe((records) => {
this.data = records;
self.instantiateDataTable();
});
}
Upvotes: 0