Search code examples
angulartypescriptag-grid-angular

unable to add data to ag-grid dynamically


I am trying to populate the rows of ag-grid dynamically.The grid must be shown only when i send a file for validation and there are some errors. Below is my code:

columnDefs = [
    {headerName: 'S.No.', field : 'SNo'},
    {headerName: 'Error Description', field: 'Error_Description'},
    {headerName: 'Suggestion', field: 'Suggestion'}
  ];

rowData = [
    // {SNo :1, Error_Description:"Error 1", Suggestion: 'Suggestion 1'},
    // {SNo :2, Error_Description:"Error 2", Suggestion: 'Suggestion 2'},
    // {SNo :3, Error_Description:"Error 3", Suggestion: 'Suggestion 3'},
    // {SNo :4, Error_Description:"Error 4", Suggestion: 'Suggestion 4'}
  ];

index.html

<ag-grid-angular [hidden]="isValid" class="ag-theme-balham" style="width: fit-content" [rowData]="rowData" [columnDefs]="columnDefs">
        <!-- Show table -->
      </ag-grid-angular>

dynamic population of grid rows

for(var i=0;i<this.errorMsgs.length;i++){
        let errorObj={};
        errorObj["SNo"]=i+1;
        errorObj["Error_Description"]=this.errorMsgs[i];
        errorObj["Suggestion"]="Put Some Suggestion"
        this.rowData.push(errorObj);
      }

When i use the hardcoded values(commented values) i get the expected output. However, when i try to populate the grid dynamically the data is not displayed. The data is pushed into the rowData but for some reason, it doesn't show in the table. What am i doing wrong? Thanks in advance and apology if this is a silly question as this is the first time i am working with ag-grid


Solution

  • This is probably Angular's change detection messing with you. When you push to an array, the contents of the array change, but Angular might not pick that up, since it usually depends on changes to reference instead of value.

    Replace:

    this.rowData.push(errorObj);
    

    with

    this.rowData = [...this.rowData, errorObj];
    

    This will "add" the new errorObj to the rowData by essentially creating a new array and reassigning the reference of the new array to rowData. It relies on the spread syntax. I also recommend reading more about Angular Change Detection.