Search code examples
angularangular-datatables

Angular 5 Datatable - refresh the column and data on button click


I am using angular data-table from angular-data-tables plugin. i have made a component for data-table seperately so that it can be used generically.

Hence providing input() columns variable to this component which is essentially responsible for creating number of column in table.

this input() columns will be passed from parent component in which data-table component is embedded. I want to change the columns name/count on basis of button click present in parent component.but when i change my columns in parent component somehow i dont know how the data-table component column becomes empty.

this is stackblitz url for the scenario Just click on changecolumn button you will see the header will become invisible.


Solution

  • This is because angular-datatables is essentially an angular wrapper for the jQuery datatable plugin (Found here: https://datatables.net/).

    According to their manual

    Any manipulation of the table after initialisation must be done through the API

    Found here https://datatables.net/manual/tech-notes/3

    angular-datatables plugin actually has APIs for supporting asynchronously loaded data. An example can be found here: https://l-lin.github.io/angular-datatables/#/basic/angular-way

    Now, for your specific example, a workaround would be to remove the table component from the DOM completely, change the columns, and then reinitialize the table component. So, in your stackblitz example:

    In app.component.html:

    <button (click)="buttonclick()">change columns</button>
    
    <hello *ngIf="showTable" [columns] = "columns"></hello>
    

    In app.component.ts, change button click function and add the showTable variable:

    showTable: boolean = true;
    buttonclick(){
        this.showTable = false;
        this.columns=["new_id","new_firstname","new_lastname"];
        setTimeout(()=>{this.showTable = true}, 0);
    }
    

    This will essentialy recreate your whole table on every single button click.