Search code examples
angulartypescriptag-gridangular6stackblitz

Ag-grid in Angular does not refresh when RowData is changed


I have fully set up an ag-grid in Angular 6 which shows all of the rowData correctly when the page is started. However, when items are added to the rowData, the display of the ag-grid doesn't update.

I have this situation set up in the following StackBlitz link:

https://stackblitz.com/edit/ag-grid-error?file=src/app/app.component.ts

I set this up so that each time the button on the top is clicked, an item is added to rowData and rowData is logged to console (accessed on the bottom right). The problem that I'm running into is that when I click the button to update rowData, the ag-grid doesn't display the new items.

Interestingly enough, if you delete any portion of code in the editor and retype it to update the display, the new items will show on the ag-grid.

Thank you in advance to anyone who knows how to solve this problem.


Solution

  • Add gridReady event to your grid HTML, And use this.gridApi.setRowData(this.rowData) to refrech grid data after new row add.

    StackBlitz solution link

    <ag-grid-angular
      style="width:100%;height:90vh"
      class="ag-theme-balham"
      [gridOptions]="gridOptions"
      [columnDefs]="columnDefs"
      (gridReady)="onGridReady($event)">
    </ag-grid-angular>
    

    Update your app.component.ts code as below

      private gridApi;
      private rowData = [];
    
      onGridReady(params) {
        this.gridApi = params.api; // To access the grids API
      }
    
      addItem() {
        this.rowData.push({ item: "item" });   // Add new Item 
        this.gridApi.setRowData(this.rowData); // Refresh grid
        console.log(this.rowData);
      }