How to hide rows without them taking space - ag-grid

I am using getRowStyle to hide the rows which don't have changes, under certain circumstances. Essentially:
const rowsToHide = [3,5,6]
function getRowStyle({node}) => {
if(!rowsToHide.includes[node.rowIndex]) {
return undefined;
}
return { display: 'none', height: 0 }
}
However, ag-grid retains the space for the hidden row regardless. How could I display only the rows I want, without leaving blank rows in the grid?

Related

Can I set an ag-grid full-width row to have autoHeight?

I am trying to render a set of footnotes at the end of my data set. Each footnote should be a full-width row. On the docs page for row height, it says that you can set an autoHeight property for the column you want to use to set the height. Full-width rows, however, aren't tied to any column, so I don't think there's a place to set that autoHeight property.
For reference, here is my cell renderer, which gets invoked if a flag in the data object is true.
import { Component } from '#angular/core';
import { ICellRendererComp, ICellRendererParams } from '#ag-grid-community/core';
#Component({
template: '',
})
export class FootnoteRendererComponent implements ICellRendererComp {
cellContent: HTMLElement;
init?(params: ICellRendererParams): void {
this.cellContent = document.createElement('div');
this.cellContent.innerHTML = params.data.title;
this.cellContent.setAttribute('class', 'footnote');
}
getGui(): HTMLElement {
return this.cellContent;
}
refresh(): boolean {
return false;
}
}
The footnote (the "title" property above) could be one line or several depending on its length and the browser's window size. There may also be several footnotes. Is there a way to set autoHeight for each footnote row? Thanks for any help!
Not sure of CSS autoHeight can be use, but here is some example for calculating height dynamically. Take a look to getRowHeight function, it's works for any rows (full-width too):
public getRowHeight: (
params: RowHeightParams
) => number | undefined | null = function (params) {
if (params.node && params.node.detail) {
var offset = 80;
var allDetailRowHeight =
params.data.callRecords.length *
params.api.getSizesForCurrentTheme().rowHeight;
var gridSizes = params.api.getSizesForCurrentTheme();
return (
allDetailRowHeight +
((gridSizes && gridSizes.headerHeight) || 0) +
offset
);
}
};
Here is the solution I ended up with, though I like #LennyLip's answer as well. It uses some ideas from Text Wrapping in ag-Grid Column Headers & Cells.
There were two parts to the problem - 1) calculating the height, and 2) knowing when to calculate the height.
1) Calculating the Height
I updated the footnote's Cell Renderer to add an ID to each footnote text node, and used it in the function below.
const footnoteRowHeightSetter = function(params): void {
const footnoteCells = document.querySelectorAll('.footnote .footnote-text');
const footnoteRowNodes = [];
params.api.forEachNode(row => {
if (row.data.dataType === 'footnote') { // Test to see if it's a footnote
footnoteRowNodes.push(row);
}
});
if (footnoteCells.length > 0 && footnoteRowNodes.length > 0) {
footnoteRowNodes.forEach(rowNode => {
const cellId = 'footnote_' + rowNode.data.id;
const cell = _.find(footnoteCells, node => node.id === cellId);
const height = cell.clientHeight;
rowNode.setRowHeight(height);
});
params.api.onRowHeightChanged();
}
};
To summarize, the function gets all HTML nodes in the DOM that are footnote text nodes. It then gets all of the table's row nodes that are footnotes. It goes through those row nodes, matching each up with its DOM text. It uses the clientHeight property of the text node and sets the row node height to that value. Finally, it calls the api.onRowHeightChanged() function to let the table know it should reposition and draw the rows.
Knowing when to calculate the height
When I set the gridOptions.getRowHeight property to the function above, it didn't work. When the function fires, the footnote rows hadn't yet been rendered, so it was unable to get the clientHeight for the text nodes since they didn't exist.
Instead, I triggered the function using these event handlers in gridOptions.
onFirstDataRendered: footnoteRowHeightSetter,
onBodyScrollEnd: footnoteRowHeightSetter,
onGridSizeChanged: footnoteRowHeightSetter,
onFirstDataRendered covers the case where footnotes are on screen when the grid first renders (short table).
onBodyScrollEnd covers the case where footnotes aren't on screen at first but the user scrolls to see them.
onGridSizeChanged covers the case of grid resizing that alters the wrapping and height of the footnote text.
This is what worked for me. I like #LennyLip's answer and looking more into it before I select an answer.

Formatting rule to change other cells based on cell value

I'm trying in Aggrid to do the following formatting:
if cell X has some value, then change the formatting of cells Y an Z (different columns, same row)
Is this possible to do ? Which functions from the API should I use ?
edit : alternatively, because my grid data won't be edited, I can also look for a way to simply define ahead of time of cells so they get displayed with a specific style, while other cells of the same column on different rows get displayed with another style (eg different font color)
Seems quite straightforward what you're trying to achieve. You need to use the cellClassRules property for your Y and Z columns, and format them appropriately, depending on the value of column X.
Here is a simple example which set the background colour of columns Y and Z to the colour specified in column X:
cellClassRules: {
'rag-red': (params) => {
return params.data.x == 'red';
},
'rag-amber': (params) => {
return params.data.x == 'amber';
},
'rag-green': (params) => {
return params.data.x == 'green';
},
},
And the definition of the css classes:
.rag-red {
background-color: lightcoral;
}
.rag-green {
background-color: lightgreen;
}
.rag-amber {
background-color: lightsalmon;
}
Demo.

Remove border-bottom for the cells in a specific column

Is there a way to remove the row seperator for a specific column. I tried overriding default styles by writing a scss mixin as shown below:
.ag-theme-balham-custom {
#include ag-theme-balham(
(
row-border-color: null,
// row-border-color: blue,
)
);
}
It is working but obviously it removes the seperator for all the grid rows. What I need to achieve is, if there are 10 columns, the row separator(bottom border) of 9th and 10th column's rows should be hidden by default and it should appear only when the header of corressponding column is hovered.
As highlighted in the image, the row seperator should be hidden for Test column and it should only appear when the Test column header is hovered.
You can do this by adding a cell-class rule to that specific column in your columnDefs i.e.
{
field: 'yourField',
cellClassRules: { 'no-border-cell' },
}
You can even apply class when your cell i.e.
cellClassRules: { 'no-border-cell': ({ data }) => data.fieldValue === 'a' }
For Row border you can use getRowStyle in your gridOptions i.e
gridOptions.getRowStyle(params) {
if (params.data.myColumnToCheck === myValueToCheck) {
return {'border': 'none'}
}
return null;
}

Row spanning not working properly when you scroll

I made some modifications in the given example in the website:
ag-Grid row spanning example
specifically, I added the following:
} else if (athlete === "Jenny Thompson") {
return 500;
...
cellClassRules: { "cell-span": "value==='Jenny Thompson' || value==='Aleksey Nemov' || value==='Ryan Lochte'" },
At first look, it seems that 'Jenny Thompson' spans properly. However, when you scroll a little bit further, the spanning stops. But if you click on 'Jenny Thompson' and scroll, the spanning continues up to the 500th cell.
The issue is that when you scroll down, the previous rows are removed and replaced by new ones. Thus, the rowSpan is removed. I did a workaround for this.
In rowData, I added these new properties: rowSpan-<index> and grpSpan-<index>. rowSpan-<index> will indicate how many rows a cell span to. I have to calculate the rowspan for the other rows under the main group cell. For example, my cell spans 50 rows. Therefore, it has a rowspan of 50. The cell below it will have a rowspan of 49, the next cell will have 48, and so on. This is so when the rows above got removed from viewport, the new cells still know how many rows it need to span. These other cells that have a rowspan less than the main (50 in this example), will have another property grpSpan-<index>. This is just to identify that they are part of the main group. By the way, index is the column index.
Then I added the following property to columnDefs:
column['rowSpan'] = (params) => {
return params.data[`rowSpan-<index>`] ? params.data[`rowSpan-<index>`] : 1;
};
column['cellClassRules'] = {
'cell-span': (params) => {
return params.data[`rowSpan-<index>`] ? true : false;
},
'cell-group': 'true',
'cont-span': (params) => {
return params.data[`grpSpan-<index>`] ? true : false;
}
};
In css:
.cell-span {
border-bottom: 1px solid #d9dcde !important;
}
.cell-group {
background: white;
}
.cont-span {
color: white;
}
I hope this helps others struggling with this issue.

How to provide a background color for an entire row in ag grid based on a certain value in a column?

I need to provide a background color for an entire row in ag grid based on a condition in a column. I found no such examples where entire row is colored based on a certain value in a column..
The previous answer is somewhat outdated (although still correct and working) and now we have some more control over the styling of the grid. You could use getRowStyle(params) for this job, just like this:
gridOptions.getRowStyle(params) {
if (params.data.myColumnToCheck === myValueToCheck) {
return {'background-color': 'yellow'}
}
return null;
}
Obviously, myColumnToCheck would be the column you're checking your value against (the same name you input in the id/field property of the colDef object), and myValueToCheck would be the value you want said column to have to make the row all yellow.
I hope this helps others. A very common use case in any table or grid including AG Grid is going to be to set the even/odd background color of the whole row of the entire table in a performant way. ALSO, this needs to still work when SORTING.
ALL OF THESE WAYS OF DOING THIS IN AG-GRID ARE WRONG. Even though they WILL work without sort, they will not update properly when you go to use sorting. This is due to something the ag-grid team refers to in this issue https://github.com/ag-grid/ag-grid-react/issues/77 as initialization time properties.
// Initialization problem
getRowClass = (params) => {
if (params.node.rowIndex % 2 === 0) {
return this.props.classes.rowEven;
}
};
<AgGridReact
getRowClass={this.getRowClass}
>
// Initialization problem
getRowStyle = (params) => {
if (params.node.rowIndex % 2 === 0) {
return this.props.classes.rowEven;
}
};
<AgGridReact
getRowStyle={this.getRowStyle}
>
// Initialization problem
rowClassRules = {
rowEven: 'node.rowIndex % 2 === 0',
}
rowClassRules = {
rowEven: (params) => params.node.rowIndex % 2 === 0,
}
<AgGridReact
rowClassRules={this.rowClassRules}
>
// Trying to change the key so a rerender happens
// Grid also listens to this so an infinite loop is likely
sortChanged = (data) => {
this.setState({ sort: Math.random()})
}
<AgGridReact
key={this.state.sort}
onSortChanged={this.sortChanged}
>
Basically, most stuff in grid is just read once and not again, probably for performance reasons to save rerenders.
You end up with this problem when sorting when doing any of the above:
THE FOLLOWIUNG IS THE RIGHT WAY TO ACHIEVE EVEN ODD COLORING:
The correct way to add even/odd functionality in ag-grid is to apply custom css styles as follows:
You will need to overwrite/use ag variables as mentioned in the docs here:https://www.ag-grid.com/javascript-grid-styling/#customizing-sass-variables
The names of the variables in our case are
.ag-grid-even class name, or the .ag-grid-odd class name. You of course only need one if you just want an alternating color to help with visibility. For our purposes we only needed one.
Here is how this process looked in our repo:
1. Make a custom css file that overwrites/uses some of these ag- class variable names. We call it ag-theme-custom.css (I believe it needs to be a css file).
Note: We also have sass variables so this file just has a comment that this color I am adding in css is the value for our variable $GREY_100 so you don't need that part
You now will get the same result but it will still work when sorting.
Answer 2 is correct, but the syntax used is wrong, and caused me several problems trying to sort it out. Trying to minify the answer 2 code barfed, for example. It did work, but it's not proper syntax as far as I can see.
Note, this can be done inline, or with an external
function. For example an external function.
vm.gridOptions = {
columnDefs: columnDefs,
getRowStyle: getRowStyleScheduled
}
function getRowStyleScheduled(params) {
if (params.selected && params.data.status === 'SCHEDULED') {
return {
'background-color': '#455A64',
'color': '#9AA3A8'
}
} else if (params.data.status === 'SCHEDULED') {
return {
'background-color': '#4CAF50',
'color': '#F4F8F5'
};
}
return null;
};
You can add CSS classes to each row in the following ways:
rowClass: Property to set CSS class for all rows. Provide either a string (class name) or array of strings (array of class names).
getRowClass: Callback to set class for each row individually.
<ag-grid-angular
[rowClass]="rowClass"
[getRowClass]="getRowClass"
/* other grid options ... */>
</ag-grid-angular>
// all rows assigned CSS class 'my-green-class'
this.rowClass = 'my-green-class';
// all even rows assigned 'my-shaded-effect'
this.getRowClass = params => {
if (params.node.rowIndex % 2 === 0) {
return 'my-shaded-effect';
}
};
You can define rules which can be applied to include certain CSS classes via the grid option rowClassRules.
The following snippet shows rowClassRules that use functions and the value from the year column:
<ag-grid-angular
[rowClassRules]="rowClassRules"
/* other grid options ... */>
</ag-grid-angular>
this.rowClassRules = {
// apply green to 2008
'rag-green-outer': function(params) { return params.data.year === 2008; },
// apply amber 2004
'rag-amber-outer': function(params) { return params.data.year === 2004; },
// apply red to 2000
'rag-red-outer': function(params) { return params.data.year === 2000; }
};
You can't change the background color of an entire row in one command. You need to do it through the cellStyle callback setup in the columnDefs. This callback will be called per each cell in the row. You need to change the color of the row by changing the color of all the cells.
See the following column definition
{
headerName: "Street Address", field: "StreetAddress", cellStyle: changeRowColor
}
You need to do this for all your columns.
Here is your changeRowColor function.
function changeRowColor(params) {
if(params.node.data[4] === 100){
return {'background-color': 'yellow'};
}
}
It changes the color of a row if the value of the third cell is 100.
I set different color for even and odd rows you can do it in any way..
$scope.gridOptions.getRowStyle = function getRowStyleScheduled(params){
if(parseInt(params.node.id)%2==0) {
return {'background-color': 'rgb(87, 90, 90)'}
}else {
return {'background-color': 'rgb(74, 72, 72)'}
}
};
If you don't need to set the background color conditionally(based on the row data), it is not recommended to use rowStyle, as written on the row style documentation page:
// set background color on even rows
// again, this looks bad, should be using CSS classes
gridOptions.getRowStyle = function(params) {
if (params.node.rowIndex % 2 === 0) {
return { background: 'red' };
}
}
Instead, you can change the row colors using css:
#import "~ag-grid-community/dist/styles/ag-grid.css";
#import "~ag-grid-community/dist/styles/ag-theme-alpine.css";
#import "~ag-grid-community/dist/styles/ag-theme-balham.css";
#import "~ag-grid-community/src/styles/ag-theme-balham/sass/ag-theme-balham-mixin";
.ag-theme-balham {
#include ag-theme-balham((
// use theme parameters where possible
odd-row-background-color: red
));
}
If you are using AdapTable then the simplest way is to use a Conditional Style and apply it to a whole row.
The advantage of this is that it can be at run-time easily by users also.
https://demo.adaptabletools.com/style/aggridconditionalstyledemo