Search code examples
angular8angular9

How to refresh the table data in angular 9


Trying to refresh the table data without empty the table data before refresh in angular but it is not working properly. How to resolve this issue.

app.component.html:

  <data-table [data]="tableData" [header]="tableHeader"></data-table>
  <button (click)="refresh()">Refresh</button>

app.component.ts:

refresh(){
         this.loadingicon=true;
         //this.tableData=[]; ->avoiding this
         //this.tableHeader = [];->avoiding this
         this.tableData=[...this.tableData];
         this.tableHeader = [...this.tableHeader];
         if(this.tableData.length != 0){
          this.loadingicon=false;
         }
      }

Solution

  • Use ChangeDetectorRef method for that.

    Define in your constructor like

    constructor(private ref: ChangeDetectorRef){ }
    

    Use in your refresh function

    refresh(){
       this.loadingicon=true;
       this.tableData=[...this.tableData];
       this.tableHeader = [...this.tableHeader];
       this.ref.markForCheck(); // use this method or
       this.ref.detectChanges(); // use this method
       if(this.tableData.length != 0){
           this.loadingicon=false;
       }
    }
    

    Please refer this link for more details.