11

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.

Luke LaValva
  • 324
  • 1
  • 3
  • 13

1 Answers1

20

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);
  }
ElasticCode
  • 7,311
  • 2
  • 34
  • 45
  • 1
    Thank you! It works! This isn't absolutely necessary for me, but do you know if it's possible to make this also work when changing the array from a different element? – Luke LaValva May 14 '18 at 00:01
  • 1
    Welcome, I hope if you can set it as an answer, what do you mean by changing the array from a different element? – ElasticCode May 14 '18 at 00:03
  • If I were to edit the array in "list.ts" from a function inside "hello.compoent.ts", would I also be able to update the ag-grid from there? – Luke LaValva May 14 '18 at 01:03
  • 1
    You can change `list.ts` to service so it will be shared with other components and you can add `rowData` to the service and add items to it from `hello.compoent.ts` then once you load the `app.component.ts` you can use list service `rowData` as a data source for the grid – ElasticCode May 14 '18 at 22:39
  • 1
    I had to better learn how to use services, but my program is working fully now. Thank you! – Luke LaValva May 18 '18 at 16:13