How to Add Controls in AG-Grid In Angular?

To add controls in an AG-Grid in Angular, you typically use cell renderers. Cell renderers allow you to define custom HTML content for a cell in the grid. Here’s how you can add controls using cell renderers in AG-Grid:

1. Install AG-Grid and AG-Grid Angular:

If you haven’t already, install AG-Grid and AG-Grid Angular in your Angular project.

npm install --save ag-grid-community ag-grid-angular

2. Create a Custom Cell Renderer Component:

Create a new Angular component to serve as the custom cell renderer. For example, let’s create a component called `ButtonRenderer`:

ng generate component ButtonRenderer

3. Implement the Custom Cell Renderer:

In the `button-renderer.component.ts` file, implement the custom cell renderer logic. This component will contain the HTML and functionality for the button:

import { Component } from '@angular/core';
import { ICellRendererAngularComp } from 'ag-grid-angular';
@Component({
selector: 'app-button-renderer',
template: `<button (click)="onClick()">Click Me</button>`,
})
export class ButtonRendererComponent implements ICellRendererAngularComp {
params: any;
agInit(params: any): void {
this.params = params;
}

onClick(): void {
// Handle button click event here
console.log('Button clicked', this.params);
}

refresh(params: any): boolean {
return false;
}
}

4. Use the Custom Cell Renderer in AG-Grid:

In your AG-Grid configuration (e.g., in your component’s HTML file), specify the custom cell renderer for the desired column:

<ag-grid-angular
[rowData]="rowData"
class="ag-theme-alpine"
[columnDefs]="columnDefs"
(gridReady)="onGridReady($event)"
></ag-grid-angular>

In your component file (e.g., `app.component.ts`), define the column definition with the custom cell renderer:

import { Component } from '@angular/core';
import { ButtonRendererComponent } from './button-renderer/button-renderer.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
columnDefs = [
{ headerName: 'ID', field: 'id' },
{ headerName: 'Name', field: 'name' },
{
headerName: 'Actions',
cellRendererFramework: ButtonRendererComponent,
},
];
rowData = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Doe' },
// Add more data as needed
];
onGridReady(params: any): void {
params.api.sizeColumnsToFit();
}
}

5. Styling (Optional):

Style your button renderer component as needed in its corresponding CSS file (`button-renderer.component.css`).

That’s it! Now, your AG-Grid will display a button in the specified column, and clicking the button will trigger the `onClick` method in the custom cell renderer component. Adjust the button’s appearance and functionality according to your requirements.