Guide to inserting an Angular routerLink within a cell in ag-Grid

When attempting to display a link on a basic HTML page, the code looks like this:

<a [routerLink]="['/leverance/detail', 13]">A new link</a>

However, when trying to render it within an ag-Grid, the approach is as follows:

src\app\leverancer\leverancer.component.ts

ngOnInit() {
    this.dataGridColumnDefs = [
          { 
            headerName: 'Type', 
            field: 'leveranceType.name', 
            width: 150,
            cellRenderer: this.customCellRendererFunc       
          }
    ];
}

customCellRendererFunc(params): string {
  const cellContent `<a [routerLink]="['/leverance/detail', 13]">A new link</a>`;
  return cellContent;
}

Despite the implementation, the routerLink does not work within my ag-Grid. Could you offer guidance on how to properly render a working routerLink in my ag-Grid?

Answer №1

It appears that the cellRenderer only allows for standard HTML and does not support any Angular-specific elements.

If you are looking to incorporate Angular components, consider using cellRendererFramework instead. Here are some examples showcasing its usage:

If you are utilizing RouterLink, ensure that you have included RouterModule in the moduleImports.

Answer №2

Innovated a versatile component that can be applied to any link cell.

Instructions for Use

columnDefs = [
  {
    colId: 'My Column',
    cellRendererFramework: AgGridLinkCellComponent,
    cellRendererParams: {
      // `text` and `link` both accept either an string expression (same as `field`) or a function that gets ICellRendererParams
      text: 'title',
      link: (params: ICellRendererParams) => `/my-path/${_.get(params, 'data.id')}`
    }
  }
]

To integrate this component into your AppModule, follow these steps:

imports: [
    AgGridModule.withComponents([
      AgGridLinkCellComponent
    ])
]

The code snippet below showcases the actual component functionality:

import * as _ from 'lodash';
import {Component} from '@angular/core';
import {AgRendererComponent} from 'ag-grid-angular';
import {ICellRendererParams} from 'ag-grid-community';

@Component({
  selector: 'app-ag-grid-link-cell-component',
  template: '<a [routerLink]="link">{{ text }}</a>',
})
export class AgGridLinkCellComponent implements AgRendererComponent {
  link: string;
  text: string;

  constructor() {
  }

  agInit(params: ICellRendererParams): void {
    this.updateDisplay(params);
  }

  updateDisplay(params: ICellRendererParams): boolean {
    const dataParams = params.colDef.cellRendererParams;
    this.link = _.isFunction(dataParams.link) ? dataParams.link(params) : _.get(params.data, dataParams.link);
    this.text = _.isFunction(dataParams.text) ? dataParams.link(params) : _.get(params.data, dataParams.text);
    return false;
  }
}

Answer №3

Here is a solution that has been tested with angular 7 and it works perfectly for me.

ag-Grid offers events and callbacks, such as onCellClicked and cellRenderer.

The issue with onCellClicked and cellRenderer is that they operate in JS, so the this object associated with these callbacks will be a JS instance.

However, in order for Angular to execute functions or navigate to any URL, we require an instance of the angular component, which is not available in these callbacks.

Therefore, here is a solution to obtain that Angular instance to work with the component.

TypeScript stores the instance of the current object in _this whenever this is not accessible. We can retrieve the instance of the Angular component using:

const self = eval('_this');

This self will contain the instance of the Angular component, allowing us to call any function or service from the Angular component and also use self.router.navigateByUrl(url)

Here is an example:

{field: 'plan', headerName: 'Plan Case', sortable:true,filter:true,
  cellRenderer:function(paramObj){
    //to create a link within the cell
    return `<a href="javascript:void(0)" >Plan Case</a>`;
  }, 
  onCellClicked:function(data){
    const self = eval('_this');
    //navigate upon clicking on the cell
    self.router.navigateByUrl('YOUR_URL');
  }  
},

Alternatively, you can call any Angular function from the onCellClicked event. For example:

onCellClicked:function(data){
        const self = eval('_this');
        //call the test function from the Angular component
        self.test(data.data);
      } 

Thank you

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for the exclusion of 'null' from the return type of Document.getElementById in VS Code?

Versions of VS Code: Experimenting with 'Type Narrowing' Code in VS Code has brought to my attention a discrepancy between the information provided by VS Code and TypeScript Playground: In VS Code, it shows that the return type of Document.getE ...

Parsing of the module has failed due to the presence of an unexpected character '' while attempting to import a video file

Trying to create a video player in NextJS using TS. I brought in a video file from my src/assets folder and encountered an error. Error - ./src/assets/video.mp4 Module parse failed: Unexpected character '' (1:0) You may need an appropriate load ...

Having trouble with implementing Spotify OAuth in NextJS?

I am in the process of creating a music website portfolio using Spotify and NextJS. I want to incorporate music playback on the website, but I am encountering issues with Spotify authentication. When I click the login button, I receive a 405 HTTP status er ...

The code snippet for the React TypeScript Cheatsheet in the Portal sample appears to be malfunction

I have implemented a strict version of TypeScript and ESLint in my project. The code for this portal was originally sourced from the documentation available here: After making some modifications, the code now looks like this: import React, { useEffect, u ...

What are the best ways to personalize my code using Angular Devextreme?

Our development team is currently utilizing Angular for the front-end framework and ASP.net for the back-end framework. They are also incorporating Devextreme and Devexpress as libraries, or similar tools. However, there seems to be difficulty in implement ...

Is there a way to retrieve the status_code 400 in Angular?

How can I determine if the status code equals 400 in Angular to display a notification? I attempted the following method: signUp() { let body = { login: this.username, nom: this.nom, prenom: this.prenom, adress: thi ...

Tips for solving the error "Angular CLI version 7.0.3 cannot install node-sass"

Every time I attempt to run npm start, an error message stating that it cannot find the module node-sass appears. Then, when I try running npm install node-sass --save, a series of errors pop up. https://i.stack.imgur.com/2I7DU.png ...

New Chrome update restricts insecure cookies from functioning in Angular

We have been utilizing the ngx-cookie-service to establish session cookies for our logged-in users. Everything was functioning properly until yesterday when the latest Chrome update began blocking unsecure cookies and displaying a warning message in the co ...

Angular error message: The property 'results' is not found on the type 'ICandidate'

I am currently working with Angular-12 and have the following code snippet: Interface: export interface ICandidate { id: number; first_name: string; other_name: string; last_name : string; email: string; gender : string; user_photo: any; m ...

Issue with Component in Angular not functioning properly with proxy construct trap

Currently working with Angular 17, I have a straightforward decorator that wraps the target with Proxy and a basic Angular component: function proxyDecorator(target: any) { return new Proxy(target, { construct(target: any, argArray: any[], newTarget: ...

Using Angular 4 in combination with Bootstrap 4 to create powerful data tables

Looking to incorporate a table using Angular 4 and Bootstrap 4, but the standard Bootstrap 4 table doesn't meet expectations. In my search for alternatives, I came across this GitHub project: https://www.npmjs.com/package/angular-4-data-table-fix Ho ...

Having issues fetching data from the store with the latest version of Ngrx

I've been trying to integrate ngrx into my Angular project, but I'm facing a challenge with retrieving and displaying data. Despite various attempts based on online resources, I can't seem to fetch the data from the store even though the sta ...

What is the best way to implement multiple pipe filters in Angular?

I am looking to filter a list of objects based on certain criteria such as status, activity, position, and category. To achieve this, I have decided to create separate pipes for each criteria: StatusPipe, ActivityPipe, PositionPipe, and CategoryPipe. I a ...

The dimensions of the div element are adjusting as I scroll on Firefox Mobile, however, there is a way to prevent this from happening using Angular

I've been conducting tests on my Angular application on various mobile devices. While everything seems to function properly on Chrome and Safari, an issue arises when it comes to Firefox: during scrolling, the browser's toolbar and URL bar appear ...

The Concept of Static Block in TypeScript

For the purpose of testing Network Encoding/Decoding Logic, I have implemented a pair of test cases in both Java and JavaScript. These tests utilize Data Providers which essentially consist of various Constants. In my Java test case, I have a Data Provide ...

Is there a way for me to steer clear of having to rely on the Elvis Operator?

Throughout my journey building my Angular 2 website, I've found the Elvis Operator to be a crucial element that makes everything possible. It seems like every task I undertake involves mastering how to apply it correctly in every instance where data i ...

Invoking a function in an Angular 4 component using a <td> element

Take a look at this block of code: personListComponent.html <tr *ngFor="let person of personService.getPersons()"> <td (onShow)="getCountry(person)">{{person.name}}</td> <td>{{country}} </tr personListComponent.ts ...

What is the Angular alternative to control.disable when working with a QueryList?

I have encountered a challenge in my Angular form where I need to disable certain fields. The issue arises from the fact that many of the HTML tags used are customized, making it difficult to simply use the disabled attribute. To address this, I have opted ...

Implementing an overlay feature upon clicking a menu item - here's how!

I am currently working on implementing an overlay that displays when clicking on a menu item, such as item 1, item 2 or item 3. I have managed to create a button (Click me) that shows an overlay when clicked. Now, I would like to achieve the same effect wh ...

Error: Unable to connect to 'ngbTypeahead' as it is not recognized as a valid attribute of 'input' in the template

Having trouble with ngbTypeahead. The console is displaying the following error message: Error: Template parse errors: Can't bind to 'ngbTypeahead' since it isn't a known property of 'input'. (" <inpu ...