Issue
I am using Ag-Grid
and I want to have a dynamic height based on the number of rows, but when it exceeds the max-height
of the grid container it should show the vertical scroll.
When I have a few rows it shrinks to fit the height of rows:
But When I have some more rows that exceed the max-height
of the grid container it must show the vertical scroll: like this
I tried to achieve the mentioned feature by using domLayout='autoHeight'
but I noticed that in this scenario, vertical scrolling will not happen.
Here is my code in stackblitz
Any Idea?
Solution
I come up with the solution to calculate the height of the grid based on its rows and then compare it with the max-height
. If the height of the grid exceeds the max-height
, then I set the dom layout to normal
, Otherwise, I set the dom layout to autoHeight
private setDynamicDomLayout(): void {
// get the rendered rows
const renderedRowCount: number = this.gridApi.getDisplayedRowCount();
const maxHeight: number = this.getMaxHeight();
const size: {
rowHeight: number;
headerHeight: number;
} = {rowHeight: 47, headerHeight:51}
// we can use this one in newer version
//this.gridApi.getSizesForCurrentTheme();
const calculatedGridHeight: number = ((renderedRowCount * size.rowHeight)
+ size.headerHeight);
if (calculatedGridHeight > maxHeight
&& renderedRowCount > 0
&& maxHeight !== 0) {
this.gridApi.setDomLayout('normal');
this.dynamicGridHeight = maxHeight;
this.isNormalDomLayout = true;
this.gridApi.resetRowHeights();
}
else {
this.gridApi.setDomLayout('autoHeight');
this.gridApi.resetRowHeights();
this.isNormalDomLayout = false;
}
this.gridApi.sizeColumnsToFit();
}
private getMaxHeight(): number {
const maxHeightStyle: string = document.defaultView
.getComputedStyle(this.hostElement.nativeElement, '')
.getPropertyValue('max-height');
if (maxHeightStyle) {
const maxHeightnumberAndunit: string[] = maxHeightStyle.split('px');
if (maxHeightnumberAndunit && maxHeightnumberAndunit.length > 0) {
return +(maxHeightnumberAndunit[0]);
}
}
return 0;
}
And in our html we have to set height
like this:
<ag-grid-angular
class="ag-theme-balham grid"
[style.height]="(isNormalDomLayout) ? dynamicGridHeight + 'px': 'calc(100% - 46px)'"
[rowData]="rowData"
[columnDefs]="columnDefs"
[modules]="modules"
[overlayNoRowsTemplate]="overlayNoRowsTemplate"
(gridReady)="gridReady($event)" >
</ag-grid-angular>
Here is a working sample: Stackblitz
Answered By - Alireza Ahmadi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.