Search code examples
angular7ag-gridangular-routerag-grid-angular

Cannot read property 'navigate' of undefined while using custom cell-renderers in ag-grid


I'm using ag-grid to render a table in my angular 7.2.1 app. The custom cell renderer is just to render an edit button in the rows that will redirect to a different page.

I've done this before in a different app on a different Angular version a while ago, but for some reason the same code in this Angular 7 app is resulting in this. I think I may be missing something really simple.

I've created a minimalist reproduction of the error I'm seeing in this stackblitz - https://stackblitz.com/edit/angular-v98mjs

If you click on the Edit button, you will see this error in the console.

ERROR Error: Cannot read property 'navigate' of undefined ag-grid versions:-

I'm using the following version for ag-grid:-

"ag-grid-angular": "^20.2.0", "ag-grid-community": "^20.2.0",

Please look at the stackblitz code in the link above for the code.


Solution

  • You needed to define onEdit with Arrow Function

    onEdit = (row): void => {
      console.log('row is being edited', {row})
        this.router.navigate(['/new-url', { id: row.incidentId }], {
            relativeTo: this.route.parent
        });
    };
    

    More example such thing: ag-grid server side infinite scrolling accessing props

    Have a look at the updated plunk: https://stackblitz.com/edit/angular-oppxte

    Without arrow function, inside onEdit function of AppComponent was not able to get reference of this.router, and hence, you were getting the error.

    Cannot read property 'navigate' of undefined

    I have also introduced RootComponent and NewComponent for better modularity in the example. Hope it will be clear with that.