Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 730
Lucas LaValva Avatar asked May 13 '18 21:05

Lucas LaValva


People also ask

How do you refresh rowData on ag-Grid?

Update the Row Data inside the grid by updating the rowData grid property or by calling the grid API setRowData() . The example below shows the data with two sets of data. Clicking the buttons toggles between the data sets.

How do I reinitialize my grid?

There is a way you can achieve this. Have a flag for ngIf at the ag-grid-angular element level, and conditionally toggle it inside your event handler. This way, the grid will be reinitialised with the updated flag. Keep in mind that there is a performance cost involved here as the grid is being reinitialised.


1 Answers

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);
  }
like image 132
ElasticCode Avatar answered Sep 16 '22 16:09

ElasticCode