How to access the value of another column in the columnDefs in an ag-Grid Angular setup?

4.2k views Asked by At

I have an ag-Grid with two columns: An ID column and a Description column. I construct the column definitions of these two columns in columnDefs in the ngOnInit() method in the TypeScript class.

In the Description column I use cellRendererFramework to render a routerLink in my ag-Grid. I use cellRendererParams to pass some necessary parameters on to my Angular renderer component. It is here in the Description column that I need to access the ID value of the ID column, and put it into cellRendererParams parameter 'resourceId'. I need this ID to be able to construct my working RouterLink.

How can I do this in the code below?

ngOnInit() {
  this.columnDefs = [

    // Column A - ID
    { 
        headerName: 'ID', 
        field: 'id', 
        width: 80, 
        sort: 'desc' 
    },

    // Column B - Description
    {
        headerName: 'Description',
        field: 'description',
        width: 150,
        cellRendererFramework: AgGridRouterLinkRendererComponent,
        cellRendererParams: {
            resourcePath: '/leverance/detail',
            resourceId: HERE-I-WOULD-LIKE-TO-ACCESS-THE-ID-VALUE-OF-THE-ID-FIELD-IN-THE-ID-COLUMN-ABOVE
    }

  ];
}
2

There are 2 answers

0
Rune Hansen On BEST ANSWER

I did not find a way to access the Id value inside ngOnInit() in the columnDefs. Instead I could get it in the agInit() method in the AgRendererComponent.

agInit(params: any): void { this.resourceId = params.data.id; }

ag-grid-router-link-renderer.component.ts

import { Component } from '@angular/core';
import { AgRendererComponent } from 'ag-grid-angular';

@Component({
  template: `
    <a [routerLink]="[params.resourcePath, resourceId]">{{
      params.value
    }}</a>
  `
})
export class AgGridRouterLinkRendererComponent implements AgRendererComponent {
  params: any;
  resourceId: number;
  agInit(params: any): void {
    this.params = params;
    this.resourceId = params.data.id;
  }
  refresh(params: any): boolean {
    return false;
  }
}
2
Huy Le On

I would define column B like this:

// Column B - Description
      {
        headerName: 'Description',
        field: 'description',
        width: 150,
        cellRendererFramework: AgGridRouterLinkRendererComponent,
        cellRendererParams(params) {
          return {
            resourcePath: '/leverance/detail',
            resourceId: params.data.id
          }
        }
      }

This way you can get any fields in other columns.