How to capture the row hover event in ag-grid? - ag-grid

I was going through the documentation of ag-grid and looks like there is no event to capture the row hover event for the grid. My requirement is to display the image on the first column when the user hovers on the row. It might be on any column of the row, not necessarily the first cell. I'm using a cell-renderer and cell-editor and performing certain actions. (For simplicity, I didn't post the cell editor code in the plunker link) How can I achieve this?
Please see the plunkr example: https://plnkr.co/edit/NfuGp3iVheuCqglz
app.component.ts:
import { Component } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';
import {KaboobMenuComponent} from './kaboob-menu.component';
#Component({
selector: 'my-app',
template: `
<ag-grid-angular
#agGrid
style="width: 100%; height: 100%;"
id="myGrid"
class="ag-theme-alpine"
[columnDefs]="columnDefs"
[defaultColDef]="defaultColDef"
[rowData]="rowData"
(gridReady)="onGridReady($event)"
[frameworkComponents]="frameworkComponents"
></ag-grid-angular>
`,
})
export class AppComponent {
private gridApi;
private gridColumnApi;
private columnDefs;
private defaultColDef;
private rowData: [];
public frameworkComponents;
constructor(private http: HttpClient) {
this.columnDefs = [
{
headerName: 'Participant',
children: [
{
headerName: '',
filter: false,
sortable: false,
editable: true,
singleClickEdit: true,
cellRenderer: 'kaboobRenderer',
},
{ field: 'athlete' },
{
field: 'age',
maxWidth: 90,
},
],
},
{
headerName: 'Details',
children: [
{ field: 'country' },
{
field: 'year',
maxWidth: 90,
},
{ field: 'date' },
{ field: 'sport' },
],
}
];
this.defaultColDef = {
flex: 1,
minWidth: 150,
resizable: true,
};
this.frameworkComponents = {
kaboobRenderer: KaboobMenuComponent
};
}
onGridReady(params) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.http
.get(
'https://raw.githubusercontent.com/ag-grid/ag-grid/master/grid-packages/ag-grid-docs/src/olympicWinners.json'
)
.subscribe(data => {
this.rowData = data;
});
}
}
kaboob-menu.component.ts (My Custom Renderer):
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-kaboob-menu',
template: `<img border="0" width="15" height="10" src="https://raw.githubusercontent.com/ag-grid/ag-grid/master/grid-packages/ag-grid-docs/src/images/smiley.png"/>`,
})
export class KaboobMenuComponent implements OnInit {
params: any;
rowData: any;
display = true;
constructor() { }
agInit(params) {
this.params = params;
this.rowData = params.data;
}
ngOnInit() {
}
onClick($event) {
if (this.params.onClick instanceof Function) {
const params = {
event: $event,
rowData: this.params.node.data
};
this.params.onClick(params);
}
}
}
I'm using the cellMouseOver event, but this event is fired when we hover on the first column and not on any other columns. I want to capture the row hover event.
Any direction would be appreciated. Thanks in advance!

I also have similar requirement. I have used CSS styling and ag-grid class names to show the content of cell on row hover:
Initially hide the content of the cell by styling (display: none for that cell)
On row hover, ag-grid adds ag-row-hover CSS class, use this class selector to show the content of the cell.
Lets imagine your image class is my-image, so you have to define the styling as below:
.my-image {
display: none;
}
/* ag-grid adds ag-row-hover class on row hover */
.ag-row-hover .my-image {
display: initial;
}
For your example, you should define these styles in your kaboob-menu.component.ts ("My Custom Renderer")
Working plunker

I would listen to cellMouseOver event emitted by the grid.
In your html: (cellMouseOver)="onCellMouseOver($event)"
In your component:
onCellMouseOver(params) {
console.log(params.rowIndex); // 0
}
The params object has a rowIndex to identify which row it is on regardless of the cell. You can manipulate your rowNode inside this onCellMouseOver

Related

ag-grid - space between column header and first row

There is a space between grid header row and first data row - how do i remove this? Thanks
My code:
<div>
<ag-grid-angular style="width: 500px; height: 500px;" [headerHeight]="0" [rowData]="rowData"
[rowSelection]="rowSelection" [rowMultiSelectWithClick]="true" [columnDefs]="columnDefs"
[floatingFiltersHeight]="0" (gridReady)="onGridReady($event)">
</ag-grid-angular>
</div>
columnDefs = [{
headerName: 'id', field: 'id', editable: true, suppressToolPanel: true, filter: false, hide: true
},
{
headerName: 'payrollcode', field: 'payrollcode', editable: true, suppressToolPanel: true, filter: false
},
{
headerName: 'select', field: 'select', editable: true, suppressToolPanel: true, filter: true, cellRendererParams: { checkbox: true }
}];
Please find code for screenshot gird below.
#Input()
displayObject: Array<any> = [];
#Input()
title = '';
columnDefs = [];
calcHeight$ = of(30);
loading$;
rowData = [];
constructor(
public activeModal: NgbActiveModal,
private calendarService: CalendarService,
private injector: Injector,
private modalService: NgbModal,
private sdToastService: SdToastService) { }
ngOnInit() {
Object.keys(this.displayObject[0]).forEach(key => {
this.columnDefs.push({ headerName: key, field: key, sortable: true, filter: true });
});
// this.rowData.concat(this.displayObject);
this.rowData = this.displayObject;
console.log(this.rowData);
}
<div style="width: 400px; height: 400px;">
<ag-grid-angular style="width: 600px; height:300px;" class="ag-theme-balham" [rowData]="rowData"
[columnDefs]="columnDefs">
</ag-grid-angular>
</div>
I added the code for the grid in the screenshot.
Here is a screenshot showing better the issue:
import { Component, Injector, Input, OnInit } from '#angular/core';
import { NgbActiveModal, NgbModal } from '#ng-bootstrap/ng-bootstrap';
import { of } from 'rxjs';
import { CalendarService } from '../calendar.service';
#Component({
selector: 'app-preview-calendars',
templateUrl: './preview-calendars.component.html',
styleUrls: ['./preview-calendars.component.css']
})
export class PreviewCalendarsComponent implements OnInit {
#Input()
displayObject: Array<any> = [];
#Input()
title = '';
columnDefs = [];
calcHeight$ = of(30);
loading$;
rowData = [];
constructor(
public activeModal: NgbActiveModal,
private calendarService: CalendarService,
private injector: Injector,
private modalService: NgbModal,
) { }
ngOnInit() {
Object.keys(this.displayObject[0]).forEach(key => {
this.columnDefs.push({ headerName: key, field: key, sortable: true, filter: true });
});
// this.rowData.concat(this.displayObject);
this.rowData = this.displayObject;
console.log(this.rowData);
}
}
<div style="width: 400px; height: 400px;">
<ag-grid-angular class="ag-theme-balham" [rowData]="rowData" [columnDefs]="columnDefs">
</ag-grid-angular>
</div>
You will see that the first row is occupies too much space and the last row is hidden - this is the issue it seems there is an empty row being displayed.
The data:
I had the exact same issue. I was embedding the grid in a prosemirror document. white-space: break-spaces is what broke ag-grid.
Setting white-space: normal !important fixed the header spacing issue.
Your problem may be caused by duplicate rows. Try adding a unique id for each element and adding getRowNodeId: data => data.id to the gridOptions.

Angular 10 ag-grid cannot set property 'setRowData' because gridOptions.api undefined

I am using following versions.
Angular CLI: 10.0.1
Node: 12.18.2
OS: win32 x64
Angular: 10.0.2
#ag-grid-community/angular#23.2.1
#ag-grid-community/all-modules#23.2.1
I am using the following way:
import { Component, OnInit, ViewChild, Output } from '#angular/core';
import { SummaryDataService } from '../services/data/summary-data.service';
import {AgGridService} from '../services/common/ag-grid.service';
import { UtilService } from '../services/common/util.service';
import { GridOptions } from '#ag-grid-community/all-modules';
import { FilterComponent } from '../common/filter/filter.component';
#Component({
selector: 'app-summary',
templateUrl: './summary.component.html',
styleUrls: ['./summary.component.css']
})
export class SummaryComponent implements OnInit {
errorMessage: any = null;
noResults: boolean;
summaryData: Array<any>;
columnDefs: any;
defaultColWidth: number = 200;
numberColWidth: number = 120;
defaultColDef: any;
innerHeight: any;
gridOptions: GridOptions;
test: any;
currentDateTo: string;
currentDateFrom: string;
pendingRequest: any;
constructor(
private summaryService: SummaryDataService,
private agGridServ: AgGridService,
private util: UtilService,
) {
this.innerHeight = 450;
this.errorMessage = null;
}
ngOnInit(): void {
this.noResults = false;
this.gridOptions = <GridOptions> {
columnDefs: this.createColumnDefs(),
onGridReady: () => {
this.gridOptions.api.sizeColumnsToFit();
},
rowHeight: 48,
headerHeight: 48,
pivotMode: true,
enableSorting: true,
enableColResize: true,
enableFilter: true,
showToolPanel: true,
enableRangeSelection: true,
sortingOrder: ['asc', 'desc'],
suppressAggFuncInHeader: true,
suppressCopyRowsToClipboard: true,
filter: 'text'
}
}
private createColumnDefs() {
return [
{
headerName: "Name",
field: "name",
width: this.defaultColWidth,
sortable: true,
resizable: true,
filter: true
},
{
// Other columns definition
}
];
}
handleUserSelection(selection) {
this.getSummaryData();
}
getSummaryData(selections: any): void {
this.summaryData = []
this.errorMessage = null;
this.noResults = false;
this.summaryService.loadSummaryData()
.subscribe (
data => {
this.summaryData = data;
this.noResults = this.summaryData.length === 0;
if(!this.gridOptions.api){
return;
}
this.gridOptions.api.setRowData(this.summaryData);
},
error => {
this.errorMessage = <any>error;
}
);
}
}
When I see the Network tab on chrome deveoper tools, the result is returned fine from the service.
The issue is at:
if(!this.gridOptions.api){
return;
}
Basically, in ngOnInit(), I am initializing the gridOptions (GridOptions); but my data is to be fetched later (based on some checks and user input).
So when I am trying to use setRowData, it fails as this.gridOptions.api is undefined.
How can I solve this?
Try setting up the api after grid initialisation.
You have to use the method onGridReady(params). You can get gridApi from the params like params.api
You have to use it as following. When the grid finished creating, it raises an event that it is ready. The event executes a function assigned to that event as seeing in the following code. According to Grid Event documentation page, the AgGridEvent has two properties, api, and columnApi. So you can take this property through the raised event's parameter, like params.api. You can assign this to whatever you want. Api property is needed to create, update, retrieve rows from the grid.
─ AgGridEvent
│ api: GridAPI, // see Grid API
│ columnApi: ColumnAPI // see Column API
Codes
<!-- IN HTML PAGE -->
<ag-grid-angular
(gridReady)='onGridReady($event)'>
</ag-grid-angular>
// in TYPE SCRIPT File
onGridReady(params: any) {
this.gridApi = params.api;
}
Actually if you still has the issue, you should paste the code where you call handleUserSelection method.
BTW, you code has an explicit issue, which may cause this.gridOptions undefined:
this.summaryService.loadSummaryData()
.subscribe (...)
You forgot to unsubscribe the observer, which may cause the issue and memory leak.

Why aren't these react-data-grid columns resizable?

I'd like to have a react-data-grid with editable data and resizable columns. Only the last column of my example can be resized.
I have combined 'Basic Editing' and 'Column Resizing' from https://adazzle.github.io/react-data-grid/docs/examples/column-resizing.
import React from 'react';
import ReactDataGrid from 'react-data-grid';
const defaultColumnProperties = {
editable: true,
resizable: true,
width: 120,
};
const columns = [
{ key: 'id', name: 'ID' },
{ key: 'title', name: 'Title' },
{ key: 'complete', name: 'Complete' },
].map(c => ({ ...c, ...defaultColumnProperties }));;
const rows = [
{ id: 0, title: 'Task 1', complete: 20 },
{ id: 1, title: 'Task 2', complete: 40 },
];
class Example extends React.Component {
state = { rows };
onGridRowsUpdated = ({ fromRow, toRow, updated }) => {
this.setState(state => {
const rows = state.rows.slice();
for (let i = fromRow; i <= toRow; i++) {
rows[i] = { ...rows[i], ...updated };
}
return { rows };
});
};
render() {
return (
<ReactDataGrid
columns={columns}
rowGetter={i => this.state.rows[i]}
rowsCount={this.state.rows.length}
minHeight={500}
onColumnResize={(idx, width) =>
console.log(`Column ${idx} has been resized to ${width}`)
}
onGridRowsUpdated={this.onGridRowsUpdated}
enableCellSelect
/>
);
}
}
I expect to be able to grab the vertical separator between column 1 and 2, and drag to widen column 1, but the only grabbable column separator is after the last column, and so the only column I can resize is the last column.
Add this line to index.html
<link rel="stylesheet" media="screen" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css">
Discovered by diffing another project with working column resizing and this problem project.
While adding Bootstrap CSS does resolve the issue, the simpler solution is to just add the piece of the BS CSS that is needed to regain the box borders:
styles.css
* {
box-sizing: border-box;
}
I just scoped it to the component that is using react-data-grid like so:
styles.scss
#myComponent {
* {
box-sizing: border-box;
}
}

Angular 6 and Ag-grid

I'm doing a test with Angular 6 and Ag-Grid. I have done an example and it paints it, I mean the css and so on.
But by doing the example below and enter the real data from my Back-end does not paint the table and comes out all the time "loading"
// package.json
"dependencies": {
"ag-grid-angular": "^19.0.0",
"ag-grid-community": "^19.0.0",
// HTML
<div class="container-fluid">
Competencias
</div>
<div class="jumbotron text-center">
<ag-grid-angular #agGrid style="width: 100%; height: 200px;" class="ag-theme-balham" [gridOptions]="gridOptions">
</ag-grid-angular>
</div>
// COMPONENT
import { Component, OnInit } from '#angular/core';
import { environment } from '#env/environment';
import { CompetenceService } from '#app/services/competence.service';
import { GridOptions } from 'ag-grid-community';
#Component({
selector: 'app-competence',
templateUrl: './competence.component.html',
styleUrls: ['./competence.component.scss'],
providers: [CompetenceService],
})
export class CompetenceComponent implements OnInit {
version: string = environment.version;
title = 'app';
rowData: any;
columnDefs: any;
competences: any[];
gridOptions: GridOptions;
constructor(private competenceService: CompetenceService) { }
ngOnInit() {
this.gridOptions = <GridOptions>{};
this.gridOptions.columnDefs = new Array;
this.gridOptions.columnDefs = [
{
headerName: 'ID',
field: 'id',
width: 100
},
{
headerName: 'Nombre',
field: 'name',
width: 200
}];
this.competenceService.competences().subscribe(response => {
this.competences = response;
this.gridOptions.rowData = new Array;
this.competences.forEach((competence) => {
this.gridOptions.rowData.push({
id: competence.id, name: competence.desc
});
});
console.log(this.gridOptions);
});
}
}
First, you need to understand the flow:
rowData - is immutable - you can't manipulate with is as with array, you can just re-create it. More info
you need to avoid using gridOptions for any action - it's only for init-configuration, for anything else - you need to use gridApi - which could be accessed on onGridReady function
(gridReady)="onGridReady($event)"
...
onGridReady(params) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
let youData = [];
this.competences.forEach((competence) => {
youData.push({id: competence.id, name: competence.desc});
});
this.gridApi.setData(youData);
}
Try as below:
#Component({
selector: "my-app",
template: `<div style="height: 100%; box-sizing: border-box;">
<ag-grid-angular
#agGrid
style="width: 100%; height: 100%;"
id="myGrid"
[rowData]="rowData"
class="ag-theme-balham"
[columnDefs]="columnDefs"
[defaultColDef]="defaultColDef"
[defaultColGroupDef]="defaultColGroupDef"
[columnTypes]="columnTypes"
[enableFilter]="true"
[floatingFilter]="true"
(gridReady)="onGridReady($event)"
></ag-grid-angular>
</div>`
})
export class AppComponent {
private gridApi;
private gridColumnApi;
private rowData: any[];
private columnDefs;
private defaultColDef;
private defaultColGroupDef;
private columnTypes;
constructor(private http: HttpClient) {
this.columnDefs = [
{
headerName: 'ID',
field: 'id',
width: 100
},
{
headerName: 'Nombre',
field: 'name',
width: 200
}
];
}
onGridReady(params) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.http
.get(
"https://raw.githubusercontent.com/ag-grid/ag-grid/master/packages/ag-grid-docs/src/olympicWinnersSmall.json"
)
.subscribe(data => {
this.rowData = data;
});
}

How to use a checkbox for a boolean data with ag-grid

I have searched for awhile now and haven't seen any real example of this.
I am using ag-grid-react and I would like for a column that holds a boolean to represent that boolean with a checkbox and update the object in the rowData when changed.
I know there is checkboxSelection and I tried using it like what I have below, but realized while it's a checkbox, it's not linked to the data and is merely for selecting a cell.
var columnDefs = [
{ headerName: 'Refunded', field: 'refunded', checkboxSelection: true,}
]
So is there a way to do what I am looking for with ag-grid and ag-grid-react?
You should use the cellRenderer property
const columnDefs = [{ headerName: 'Refunded',
field: 'refunded',
editable:true,
cellRenderer: params => {
return `<input type='checkbox' ${params.value ? 'checked' : ''} />`;
}
}];
I was stuck in the same problem , this is the best I could come up with but I wasn't able to bind the value to this checkbox.
I set the cell property editable to true , now if you want to change the actual value you have to double click the cell and type true or false.
but this is as far as I went and I decided to help you , I know it doesn't 100% solve it all but at least it solved the data presentation part.
incase you found out how please share your answers with us.
What about this? It's on Angular and not on React, but you could get the point:
{
headerName: 'Enabled',
field: 'enabled',
cellRendererFramework: CheckboxCellComponent
},
And here is the checkboxCellComponent:
#Component({
selector: 'checkbox-cell',
template: `<input type="checkbox" [checked]="params.value" (change)="onChange($event)">`,
styleUrls: ['./checkbox-cell.component.css']
})
export class CheckboxCellComponent implements AfterViewInit, ICellRendererAngularComp {
#ViewChild('.checkbox') checkbox: ElementRef;
public params: ICellRendererParams;
constructor() { }
agInit(params: ICellRendererParams): void {
this.params = params;
}
public onChange(event) {
this.params.data[this.params.colDef.field] = event.currentTarget.checked;
}
}
Let me know
We can use cellRenderer to show checkbox in grid, which will work when you want to edit the field also. Grid will not update the checkbox box value in the gridoption - rowdata directly till you do not update node with respective field in node object which can be access by params object.
params.node.data.fieldName = params.value;
here fieldName is field of the row.
{
headerName: "display name",
field: "fieldName",
cellRenderer: function(params) {
var input = document.createElement('input');
input.type="checkbox";
input.checked=params.value;
input.addEventListener('click', function (event) {
params.value=!params.value;
params.node.data.fieldName = params.value;
});
return input;
}
}
Here's how to create an agGrid cell renderer in Angular to bind one of your columns to a checkbox.
This answer is heavily based on the excellent answer from user2010955's answer above, but with a bit more explanation, and brought up-to-date with the latest versions of agGrid & Angular (I was receiving an error using his code, before adding the following changes).
And yes, I know this question was about the React version of agGrid, but I'm sure I won't be the only Angular developer who stumbles on this StackOverflow webpage out of desperation, trying to find an Angular solution to this problem.
(Btw, I can't believe it's 2020, and agGrid for Angular doesn't come with a checkbox renderer included by default. Seriously ?!!)
First, you need to define a renderer component:
import { Component } from '#angular/core';
import { ICellRendererAngularComp } from 'ag-grid-angular';
import { ICellRendererParams } from 'ag-grid-community';
#Component({
selector: 'checkbox-cell',
template: `<input type="checkbox" [checked]="params.value" (change)="onChange($event)">`
})
export class CheckboxCellRenderer implements ICellRendererAngularComp {
public params: ICellRendererParams;
constructor() { }
agInit(params: ICellRendererParams): void {
this.params = params;
}
public onChange(event) {
this.params.data[this.params.colDef.field] = event.currentTarget.checked;
}
refresh(params: ICellRendererParams): boolean {
return true;
}
}
Next, you need to tell your #NgModule about it:
import { CheckboxCellRenderer } from './cellRenderers/CheckboxCellRenderer';
. . .
#NgModule({
declarations: [
AppComponent,
CheckboxCellRenderer
],
imports: [
BrowserModule,
AgGridModule.withComponents([CheckboxCellRenderer])
],
providers: [],
bootstrap: [AppComponent]
})
In your Component which is displaying the agGrid, you need to import your renderer:
import { CheckboxCellRenderer } from './cellRenderers/CheckboxCellRenderer';
Let's define a new columns for our grid, some of which will use this new renderer:
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
#ViewChild('exampleGrid', {static: false}) agGrid: AgGridAngular;
columnDefs = [
{ headerName: 'Last name', field: 'lastName', editable: true },
{ headerName: 'First name', field: 'firstName', editable: true },
{ headerName: 'Subscribed', field: 'subscribed', cellRenderer: 'checkboxCellRenderer' },
{ headerName: 'Is overweight', field: 'overweight', cellRenderer: 'checkboxCellRenderer' }
];
frameworkComponents = {
checkboxCellRenderer: CheckboxCellRenderer
}
}
And now, when you're creating your agGrid, you need to tell it about the home-made framework components which you're using:
<ag-grid-angular #exampleGrid
style="height: 400px;"
class="ag-theme-material"
[rowData]="rowData"
[columnDefs]="columnDefs"
[frameworkComponents]="frameworkComponents" >
</ag-grid-angular>
Phew!
Yeah... it took me a while to work out how to make all the pieces fit together. agGrid's own website really should've included an example like this...
The code below helps address the issue. The downside is that the normal events in gridOptions will not fired (onCellEditingStarted, onCellEditingStopped,onCellValueChanged etc).
var columnDefs = [...
{headerName: "Label", field: "field",editable: true,
cellRenderer: 'booleanCellRenderer',
cellEditor:'booleanEditor'
}
];
//register the components
$scope.gridOptions = {...
components:{
booleanCellRenderer:BooleanCellRenderer,
booleanEditor:BooleanEditor
}
};
function BooleanCellRenderer() {
}
BooleanCellRenderer.prototype.init = function (params) {
this.eGui = document.createElement('span');
if (params.value !== "" || params.value !== undefined || params.value !== null) {
var checkedStatus = params.value ? "checked":"";
var input = document.createElement('input');
input.type="checkbox";
input.checked=params.value;
input.addEventListener('click', function (event) {
params.value=!params.value;
//checked input value has changed, perform your update here
console.log("addEventListener params.value: "+ params.value);
});
this.eGui.innerHTML = '';
this.eGui.appendChild( input );
}
};
BooleanCellRenderer.prototype.getGui = function () {
return this.eGui;
};
function BooleanEditor() {
}
BooleanEditor.prototype.init = function (params) {
this.container = document.createElement('div');
this.value=params.value;
params.stopEditing();
};
BooleanEditor.prototype.getGui = function () {
return this.container;
};
BooleanEditor.prototype.afterGuiAttached = function () {
};
BooleanEditor.prototype.getValue = function () {
return this.value;
};
BooleanEditor.prototype.destroy = function () {
};
BooleanEditor.prototype.isPopup = function () {
return true;
};
React specific solution
When using React (16.x) functional component with React Hooks make it easy to write your cellRenderer. Here is the function equivalent of what pnunezcalzado had posted earlier.
React component for the cell Renderer
function AgGridCheckbox (props) {
const boolValue = props.value && props.value.toString() === 'true';
const [isChecked, setIsChecked] = useState(boolValue);
const onChanged = () => {
props.setValue(!isChecked);
setIsChecked(!isChecked);
};
return (
<div>
<input type="checkbox" checked={isChecked} onChange={onChanged} />
</div>
);
}
Using it in your grid
Adjust your column def (ColDef) to use this cell renderer.
{
headerName: 'My Boolean Field',
field: 'BOOLFIELD',
cellRendererFramework: AgGridCheckbox,
editable: true,
},
Frameworks - React/Angular/Vue.js
You can easily integrate cell renderers with any JavaScript framework you're using to render ag-Grid, by creating your cell renderers as native framework components.
See this implemented in React in the code segment below:
export default class extends Component {
constructor(props) {
super(props);
this.checkedHandler = this.checkedHandler.bind(this);
}
checkedHandler() {
let checked = event.target.checked;
let colId = this.props.column.colId;
this.props.node.setDataValue(colId, checked);
}
render() {
return (
<input
type="checkbox"
onClick={this.checkedHandler}
checked={this.props.value}
/>
)
}
}
Note: There are no required lifecycle methods when creating cell renderers as framework components.
After creating the renderer, we register it to ag-Grid in gridOptions.frameworkComponents and define it on the desired columns:
// ./index.jsx
this.frameworkComponents = {
checkboxRenderer: CheckboxCellRenderer,
};
this.state = {
columnDefs: [
// ...
{
headerName: 'Registered - Checkbox',
field: 'registered',
cellRenderer: 'checkboxRenderer',
},
// ...
]
// ....
Please see below live samples implemented in the most popular JavaScript frameworks (React, Angular, Vue.js):
React demo.
Angular demo.
Note: When using Angular it is also necessary to pass custom renderers to the #NgModule decorator to allow for dependency injection.
Vue.js demo.
Vanilla JavaScript
You can also implement the checkbox renderer using JavaScript.
In this case, the checkbox renderer is constructed using a JavaScript Class. An input element is created in the ag-Grid init lifecycle method (required) and it's checked attribute is set to the underlying boolean value of the cell it will be rendered in. A click event listener is added to the checkbox which updates this underlying cell value whenever the input is checked/unchecked.
The created DOM element is returned in the getGui (required) lifecycle hook. We have also done some cleanup in the destroy optional lifecycle hook, where we remove the click listener.
function CheckboxRenderer() {}
CheckboxRenderer.prototype.init = function(params) {
this.params = params;
this.eGui = document.createElement('input');
this.eGui.type = 'checkbox';
this.eGui.checked = params.value;
this.checkedHandler = this.checkedHandler.bind(this);
this.eGui.addEventListener('click', this.checkedHandler);
}
CheckboxRenderer.prototype.checkedHandler = function(e) {
let checked = e.target.checked;
let colId = this.params.column.colId;
this.params.node.setDataValue(colId, checked);
}
CheckboxRenderer.prototype.getGui = function(params) {
return this.eGui;
}
CheckboxRenderer.prototype.destroy = function(params) {
this.eGui.removeEventListener('click', this.checkedHandler);
}
After creating our renderer we simply register it to ag-Grid in our gridOptions.components object:
gridOptions.components = {
checkboxRenderer: CheckboxRenderer
}
And define the renderer on the desired column:
gridOptions.columnDefs = [
// ...
{
headerName: 'Registered - Checkbox',
field: 'registered',
cellRenderer: 'checkboxRenderer',
},
// ...
Please see this implemented in the demo below:
Vanilla JavaScript.
Read the full blog post on our website or check out our documentation for a great variety of scenarios you can implement with ag-Grid.
Ahmed Gadir | Developer # ag-Grid
Here is a react hooks version, set columnDef.cellEditorFramework to this component.
import React, {useEffect, forwardRef, useImperativeHandle, useRef, useState} from "react";
export default forwardRef((props, ref) => {
const [value, setValue] = useState();
if (value !== ! props.value) {
setValue(!props.value);
}
const inputRef = useRef();
useImperativeHandle(ref, () => {
return {
getValue: () => {
return value;
}
};
});
const onChange= e => {
setValue(!value);
}
return (<div style={{paddingLeft: "15px"}}><input type="checkbox" ref={inputRef} defaultChecked={value} onChange={onChange} /></div>);
})
I also have the following cell renderer which is nice
cellRenderer: params => {
return `<i class="fa fa-${params.value?"check-":""}square-o" aria-hidden="true"></i>`;
},
In the columnDefs, add a checkbox column. Don't need set the cell property editable to true
columnDefs: [
{ headerName: '', field: 'checkbox', cellRendererFramework: CheckboxRenderer, width:30},
...]
The CheckboxRenderer
export class CheckboxRenderer extends React.Component{
constructor(props) {
super(props);
this.state={
value:props.value
};
this.handleCheckboxChange=this.handleCheckboxChange.bind(this);
}
handleCheckboxChange(event) {
this.props.data.checkbox=!this.props.data.checkbox;
this.setState({value: this.props.data.checkbox});
}
render() {
return (
<Checkbox
checked={this.state.value}
onChange={this.handleCheckboxChange}></Checkbox>);
}
}
The array of the string values doesn't work for me, but array of [true,false] is working.
{
headerName: 'Refunded',
field: 'refunded',
cellEditor: 'popupSelect',
cellEditorParams: {
cellRenderer: RefundedCellRenderer,
values: [true, false]
}
},
function RefundedCellRenderer(params) {
return params.value;
}
You can use boolean (true or false)
I try this and it's work :
var columnDefs = [
{
headerName: 'Refunded',
field: 'refunded',
editable: true,
cellEditor: 'booleanEditor',
cellRenderer: booleanCellRenderer
},
];
Function checkbox editor
function getBooleanEditor() {
// function to act as a class
function BooleanEditor() {}
// gets called once before the renderer is used
BooleanEditor.prototype.init = function(params) {
// create the cell
var value = params.value;
this.eInput = document.createElement('input');
this.eInput.type = 'checkbox';
this.eInput.checked = value;
this.eInput.value = value;
};
// gets called once when grid ready to insert the element
BooleanEditor.prototype.getGui = function() {
return this.eInput;
};
// focus and select can be done after the gui is attached
BooleanEditor.prototype.afterGuiAttached = function() {
this.eInput.focus();
this.eInput.select();
};
// returns the new value after editing
BooleanEditor.prototype.getValue = function() {
return this.eInput.checked;
};
// any cleanup we need to be done here
BooleanEditor.prototype.destroy = function() {
// but this example is simple, no cleanup, we could
// even leave this method out as it's optional
};
// if true, then this editor will appear in a popup
BooleanEditor.prototype.isPopup = function() {
// and we could leave this method out also, false is the default
return false;
};
return BooleanEditor;
}
And then booleanCellRenderer function
function booleanCellRenderer(params) {
var value = params.value ? 'checked' : 'unchecked';
return '<input disabled type="checkbox" '+ value +'/>';
}
Let the grid know which columns and what data to use
var gridOptions = {
columnDefs: columnDefs,
pagination: true,
defaultColDef: {
filter: true,
resizable: true,
},
onGridReady: function(params) {
params.api.sizeColumnsToFit();
},
onCellValueChanged: function(event) {
if (event.newValue != event.oldValue) {
// do stuff
// such hit your API update
event.data.refunded = event.newValue; // Update value of field refunded
}
},
components:{
booleanCellRenderer: booleanCellRenderer,
booleanEditor: getBooleanEditor()
}
};
Setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function() {
var gridDiv = document.querySelector('#myGrid');
// create the grid passing in the div to use together with the columns & data we want to use
new agGrid.Grid(gridDiv, gridOptions);
fetch('$urlGetData').then(function(response) {
return response.json();
}).then(function(data) {
gridOptions.api.setRowData(data);
})
});
Even though it's an old question, I developed a solution that may be interesting.
You can create a cell renderer component for the checkbox then apply it to the columns that must render a checkbox based on a boolean value.
Check the example below:
/*
CheckboxCellRenderer.js
Author: Bruno Carvalho da Costa (brunoccst)
*/
/*
* Function to work as a constructor.
*/
function CheckboxCellRenderer() {}
/**
* Initializes the cell renderer.
* #param {any} params Parameters from AG Grid.
*/
CheckboxCellRenderer.prototype.init = function(params) {
// Create the cell.
this.eGui = document.createElement('span');
this.eGui.classList.add("ag-icon");
var node = params.node;
var colId = params.column.colId;
// Set the "editable" property to false so it won't open the default cell editor from AG Grid.
if (params.colDef.editableAux == undefined)
params.colDef.editableAux = params.colDef.editable;
params.colDef.editable = false;
// Configure it accordingly if it is editable.
if (params.colDef.editableAux) {
// Set the type of cursor.
this.eGui.style["cursor"] = "pointer";
// Add the event listener to the checkbox.
function toggle() {
var currentValue = node.data[colId];
node.setDataValue(colId, !currentValue);
// TODO: Delete this log.
console.log(node.data);
}
this.eGui.addEventListener("click", toggle);
}
// Set if the checkbox is checked.
this.refresh(params);
};
/**
* Returns the GUI.
*/
CheckboxCellRenderer.prototype.getGui = function() {
return this.eGui;
};
/**
* Refreshes the element according to the current data.
* #param {any} params Parameters from AG Grid.
*/
CheckboxCellRenderer.prototype.refresh = function(params) {
var checkedClass = "ag-icon-checkbox-checked";
var uncheckedClass = "ag-icon-checkbox-unchecked";
// Add or remove the classes according to the value.
if (params.value) {
this.eGui.classList.remove(uncheckedClass);
this.eGui.classList.add(checkedClass);
} else {
this.eGui.classList.remove(checkedClass);
this.eGui.classList.add(uncheckedClass);
}
// Return true to tell the grid we refreshed successfully
return true;
}
/*
The code below does not belong to the CheckboxCellRenderer.js anymore.
It is the main JS that creates the AG Grid instance and structure.
*/
// specify the columns
var columnDefs = [{
headerName: "Make",
field: "make"
}, {
headerName: "Model",
field: "model"
}, {
headerName: "Price",
field: "price"
}, {
headerName: "In wishlist (editable)",
field: "InWishlist",
cellRenderer: CheckboxCellRenderer
}, {
headerName: "In wishlist (not editable)",
field: "InWishlist",
cellRenderer: CheckboxCellRenderer,
editable: false
}];
// specify the data
var rowData = [{
make: "Toyota",
model: "Celica",
price: 35000,
InWishlist: true
}, {
make: "Toyota 2",
model: "Celica 2",
price: 36000,
InWishlist: false
}];
// let the grid know which columns and what data to use
var gridOptions = {
columnDefs: columnDefs,
defaultColDef: {
editable: true
},
rowData: rowData,
onGridReady: function() {
gridOptions.api.sizeColumnsToFit();
}
};
// wait for the document to be loaded, otherwise
// ag-Grid will not find the div in the document.
document.addEventListener("DOMContentLoaded", function() {
// lookup the container we want the Grid to use
var eGridDiv = document.querySelector('#myGrid');
// create the grid passing in the div to use together with the columns & data we want to use
new agGrid.Grid(eGridDiv, gridOptions);
});
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/ag-grid/dist/ag-grid.js"></script>
</head>
<body>
<div id="myGrid" style="height: 115px;" class="ag-fresh"></div>
</body>
</html>
Please note that I needed to disable the editable property before ending the init function or else AG Grid would render the default cell editor for the field, having a weird behavior.
import React, { Component } from 'react';
export class CheckboxRenderer extends Component {
constructor(props) {
super(props);
if (this.props.colDef.field === 'noRestrictions') {
this.state = {
value: true,
disable: false
};
}
else if (this.props.colDef.field === 'doNotBuy') {
this.state = {
value: false,
disable: true
};
}
this.handleCheckboxChange = this.handleCheckboxChange.bind(this);
}
handleCheckboxChange(event) {
//this.props.data.checkbox=!this.props.data.checkbox; ={this.state.show}
//this.setState({value: this.props.data.checkbox});
if (this.state.value) { this.setState({ value: false }); }
else { this.setState({ value: true }); }
alert(this.state.value);
//check for the last row and check for the columnname and enable the other columns
}
render() {
return (
<input type= 'checkbox' checked = { this.state.value } disabled = { this.state.disable } onChange = { this.handleCheckboxChange } />
);
}
}
export default CheckboxRenderer;
import React, { Component } from 'react';
import './App.css';
import { AgGridReact } from 'ag-grid-react';
import CheckboxRenderer from './CheckboxRenderer';
import 'ag-grid/dist/styles/ag-grid.css';
import 'ag-grid/dist/styles/ag-theme-balham.css';
class App extends Component {
constructor(props) {
super(props);
let enableOtherFields = false;
this.state = {
columnDefs: [
{ headerName: 'Make', field: 'make' },
{
headerName: 'noRestrictions', field: 'noRestrictions',
cellRendererFramework: CheckboxRenderer,
cellRendererParams: { checkedVal: true, disable: false },
onCellClicked: function (event) {
// event.node.columnApi.columnController.gridColumns[1].colDef.cellRendererParams.checkedVal=!event.node.columnApi.columnController.gridColumns[1].colDef.cellRendererParams.checkedVal;
// event.node.data.checkbox=!event.data.checkbox;
let currentNode = event.node.id;
event.api.forEachNode((node) => {
if (node.id === currentNode) {
node.data.checkbox = !node.data.checkbox;
}
//if(!node.columnApi.columnController.gridColumns[1].colDef.cellRendererParams.checkedVal){ // checkbox is unchecked
if (node.data.checkbox === false && node.data.checkbox !== 'undefined') {
enableOtherFields = true;
} else {
enableOtherFields = false;
}
//alert(node.id);
//alert(event.colDef.cellRendererParams.checkedVal);
}); alert("enable other fields:" + enableOtherFields);
}
},
{
headerName: 'doNotBuy', field: 'doNotBuy',
cellRendererFramework: CheckboxRenderer,
cellRendererParams: { checkedVal: false, disable: true }
},
{ headerName: 'Price', field: 'price', editable: true }
],
rowData: [
{ make: "Toyota", noRestrictions: true, doNotBuy: false, price: 35000 },
{ make: "Ford", noRestrictions: true, doNotBuy: false, price: 32000 },
{ make: "Porsche", noRestrictions: true, doNotBuy: false, price: 72000 }
]
};
}
componentDidMount() {
}
render() {
return (
<div className= "ag-theme-balham" style = {{ height: '200px', width: '800px' }}>
<AgGridReact enableSorting={ true }
enableFilter = { true}
//pagination={true}
columnDefs = { this.state.columnDefs }
rowData = { this.state.rowData } >
</AgGridReact>
</div>
);
}
}
export default App;
Boolean data in present part:
function booleanCellRenderer(params) {
var valueCleaned = params.value;
if (valueCleaned === 'T') {
return '<input type="checkbox" checked/>';
} else if (valueCleaned === 'F') {
return '<input type="checkbox" unchecked/>';
} else if (params.value !== null && params.value !== undefined) {
return params.value.toString();
} else {
return null;
}
}
var gridOptions = {
...
components: {
booleanCellRenderer: booleanCellRenderer,
}
};
gridOptions.api.setColumnDefs(
colDefs.concat(JSON.parse('[{"headerName":"Name","field":"Field",
"cellRenderer": "booleanCellRenderer"}]')));
Here's a solution that worked for me. It's mandatory to respect arrow functions to solve context issues.
Component:
import React from "react";
class AgGridCheckbox extends React.Component {
state = {isChecked: false};
componentDidMount() {
let boolValue = this.props.value.toString() === "true";
this.setState({isChecked: boolValue});
}
onChanged = () => {
const checked = !this.state.isChecked;
this.setState({isChecked: checked});
this.props.setValue(checked);
};
render() {
return (
<div>
<input type={"checkbox"} checked={this.state.isChecked} onChange={this.onChanged}/>
</div>
);
}
}
export default AgGridCheckbox;
Column definition object inside columnDefs array:
{
headerName: "yourHeaderName",
field: "yourPropertyNameInsideDataObject",
cellRendererFramework: AgGridCheckbox
}
JSX calling ag-grid:
<div
className="ag-theme-balham"
>
<AgGridReact
defaultColDef={defaultColDefs}
columnDefs={columnDefs}
rowData={data}
/>
</div>
I found a good online example for this feature:
https://stackblitz.com/edit/ag-grid-checkbox?embed=1&file=app/ag-grid-checkbox/ag-grid-checkbox.component.html
The background knowledge is based on the cellRendererFramework : https://www.ag-grid.com/javascript-grid-components/
gridOptions = {
onSelectionChanged: (event: any) => {
let rowData = [];
event.api.getSelectedNodes().forEach(node => {
rowDate = [...rowData, node.data];
});
console.log(rowData);
}
}
You can keep a checkbox on display and edit as following:
headerName: 'header name',
field: 'field',
filter: 'agTextColumnFilter',
cellRenderer: params => this.checkBoxCellEditRenderer(params),
And then create an renderer:
checkBoxCellEditRenderer(params) {
const input = document.createElement('input');
input.type = 'checkbox';
input.checked = params.value;
input.addEventListener('click', () => {
params.value = !params.value;
params.node.data[params.coldDef.field] = params.value;
// you can add here code
});
return input;
}
This is an old question but there is a new answer available if you are using AdapTable in conjunction with AG Grid.
Simply define the column as a Checkbox Column and AdapTable will do it all for you - create the checkbox, check it if the cell value is true, and fire an event each time it is checked:
See: https://demo.adaptabletools.com/formatcolumn/aggridcheckboxcolumndemo
So in the end I somewhat got what I wanted, but in a slightly different way, I used popupSelect and cellEditorParams with values: ['true', 'false']. Of course I don't have an actual check box like I wanted, but it behaves good enough for what I need
{
headerName: 'Refunded',
field: 'refunded',
cellEditor: 'popupSelect',
cellEditorParams: {
cellRenderer: RefundedCellRenderer,
values: ['true', 'false']
}
},
function RefundedCellRenderer(params) {
return params.value;
}