Angular Datatables with *ngIf shows error

Viewed 1556

I am using Angular Datatables to show some tabular data. I have added an *ngIf condition to the table, so that it will not be visible until the data is loaded completely. The table code looks like the following :

<table class="table" id="releaseDatatable" datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" *ngIf="!loading">

The loading variable I am setting from my component and then calling this.dtTrigger.next(). I have the following code to set loading.

set loading(loading: boolean) {
        this._loading = loading;
       setTimeout(()=>{
            this.dtTrigger.next();
       }, 100);
    }

Now for the first time, everything is working fine. But when I try to re-load the table (after edit or delete), it it is showing the following error :

ERROR ObjectUnsubscribedErrorImpl {message: "object unsubscribed", name: "ObjectUnsubscribedError"} 

and this.dtTrigger has null as observers. How this can be fixed ? I tried to re-render the table, but it is also not working.

3 Answers

You can use [ngClass] and hide rather than using ngIf

<table class="table" id="releaseDatatable" datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" [ngClass]="loading">

in component make loading attribute as "hide" or "show";

in css hide it

.hide{
   display:none;
}

For render again I use destroy and and trigger next

import

  import { DataTableDirective } from 'angular-datatables';

  @ViewChild(DataTableDirective, {static: false})  
   datatableElement: DataTableDirective;

to render

rerender(){
        this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
            dtInstance.destroy();
            this.dtTrigger.next();
        });       
    }

call this rerender method

set loading(loading: boolean) {
       setTimeout(()=>{
            this.rerender();
       }, 100);
    }

It's better to add a wrapper div for your table like <div *ngIf="!loading"><table></table></div>

Angular v2 doesn't support more than one structural directive on the same element.

Related