Set the width, height and scrolling behaviour of the grid.
<!-- set width using percentages -->
<ag-grid-angular style="width: 100%; height: 100%;" />
<!-- OR set width using fixed pixels -->
<ag-grid-angular style="width: 500px; height: 200px" />If using % for your height, then make sure the container you are putting the grid into also has height specified, as the browser will fit the div according to a percentage of the parent's height, and if the parent has no height, then this % will always be zero.
If your grid is not the size you think it should be then put a border on the grid's div and see if that's the size you want (the grid will fill this div). If it is not the size you want, then you have a CSS layout issue in your application.
DOM Layout Copy Link
There are three DOM Layout values the grid can have 'normal', 'autoHeight' and 'print'. They are used as follows:
- normal: This is the default if nothing is specified. The grid fits the width and height of the div you provide and scrolls in both directions.
- autoHeight: The grid's height is set to fit the number of rows so no vertical scrollbar is provided by the grid. The grid scrolls horizontally as normal. Note that if using this with the SSRM the grid will attempt to load every row and may cause undesired side-effects (such as excessive datasource requests or too many loaded rows).
- print: No scroll bars are used and the grid renders all rows and columns. This layout is explained in Printing.
Normal Layout Copy Link
If the width and / or height change after the grid is initialised, the grid will automatically resize to fill the new area.
The example below shows setting the grid size and then changing it as the user selects the buttons.
import { NgStyle } from "@angular/common";
import { HttpClient } from "@angular/common/http";
import type { OnInit } from "@angular/core";
import { Component, ViewChild } from "@angular/core";
import { AgGridAngular } from "ag-grid-angular";
import type { ColDef } from "ag-grid-community";
import {
ClientSideRowModelModule,
ModuleRegistry,
enableDevValidations,
} from "ag-grid-community";
import "./styles.css";
// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
enableDevValidations();
}
ModuleRegistry.registerModules([ClientSideRowModelModule]);
@Component({
standalone: true,
imports: [AgGridAngular, NgStyle],
selector: "my-app",
template: `
<div style="height: 100%; display: flex; flex-direction: column;">
<div style="margin-bottom: 5px;">
<button (click)="fillLarge()">Fill 100%</button>
<button (click)="fillMedium()">Fill 60%</button>
<button (click)="fillExact()">Exactly 400 x 400 pixels</button>
</div>
<div [ngStyle]="style">
<ag-grid-angular
style="width: 100%; height:100%;"
#agGrid
[rowData]="rowData"
[columnDefs]="columnDefs"
/>
</div>
</div>
`,
})
export class AppComponent implements OnInit {
@ViewChild("agGrid") agGrid!: AgGridAngular<IOlympicData>;
public style: any = {
width: "100%",
height: "100%",
flex: "1 1 auto",
};
public columnDefs: ColDef[] = [
{ field: "athlete", width: 150 },
{ field: "age", width: 90 },
{ field: "country", width: 150 },
{ field: "year", width: 90 },
{ field: "date", width: 150 },
{ field: "sport", width: 150 },
{ field: "gold", width: 100 },
{ field: "silver", width: 100 },
{ field: "bronze", width: 100 },
{ field: "total", width: 100 },
];
public rowData!: IOlympicData[];
constructor(private http: HttpClient) {}
ngOnInit() {
this.http
.get<
IOlympicData[]
>("https://www.ag-grid.com/example-assets/olympic-winners.json")
.subscribe((data) => {
this.rowData = data;
});
}
fillLarge() {
this.setWidthAndHeight("100%", "100%");
}
fillMedium() {
this.setWidthAndHeight("60%", "60%");
}
fillExact() {
this.setWidthAndHeight("400px", "400px");
}
setWidthAndHeight(width: string, height: string) {
this.style = {
width: width,
height: height,
};
}
}
.example-wrapper {
display: flex;
flex-direction: column;
height: 100%;
}
.grid-wrapper {
flex: 1 1 0px;
width: 100%;
}
#myGrid {
height: 100%;
}
export interface IOlympicData {
athlete: string,
age: number,
country: string,
year: number,
date: string,
sport: string,
gold: number,
silver: number,
bronze: number,
total: number
} import '@angular/compiler';
import { provideHttpClient } from '@angular/common/http';
import { enableProdMode } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
if (new URLSearchParams(window.location.search).get('prod') !== 'false') {
enableProdMode();
}
const app = bootstrapApplication(AppComponent, {
providers: [provideHttpClient()],
});
Dynamic Resizing without Horizontal Scroll Copy Link
Sometimes you want to have columns that don't fit in the current viewport to simply be hidden altogether with no horizontal scrollbar.
To achieve this determine the width of the grid and work out how many columns could fit in that space, hiding any that don't fit, constantly updating based on the gridSizeChanged event firing, like the next example shows.
This example is best seen when opened in a new tab - then change the horizontal size of the browser and watch as columns hide/show based on the current grid size.
import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { AgGridAngular } from "ag-grid-angular";
import {
ClientSideRowModelModule,
ColDef,
ColGroupDef,
ColumnApiModule,
ColumnAutoSizeModule,
FirstDataRenderedEvent,
GridApi,
GridOptions,
GridReadyEvent,
GridSizeChangedEvent,
ModuleRegistry,
enableDevValidations,
} from "ag-grid-community";
if (process.env.NODE_ENV !== "production") {
enableDevValidations();
}
ModuleRegistry.registerModules([
ColumnAutoSizeModule,
ColumnApiModule,
ClientSideRowModelModule,
]);
import { IOlympicData } from "./interfaces";
@Component({
selector: "my-app",
standalone: true,
imports: [AgGridAngular],
template: `<div id="grid-wrapper" style="width: 100%; height: 100%">
<ag-grid-angular
style="width: 100%; height: 100%;"
[columnDefs]="columnDefs"
[rowData]="rowData"
(gridSizeChanged)="onGridSizeChanged($event)"
(firstDataRendered)="onFirstDataRendered($event)"
(gridReady)="onGridReady($event)"
/>
</div> `,
})
export class AppComponent {
columnDefs: ColDef[] = [
{ field: "athlete", minWidth: 150 },
{ field: "age", minWidth: 70, maxWidth: 90 },
{ field: "country", minWidth: 130 },
{ field: "year", minWidth: 70, maxWidth: 90 },
{ field: "date", minWidth: 120 },
{ field: "sport", minWidth: 120 },
{ field: "gold", minWidth: 80 },
{ field: "silver", minWidth: 80 },
{ field: "bronze", minWidth: 80 },
{ field: "total", minWidth: 80 },
];
rowData!: IOlympicData[];
constructor(private http: HttpClient) {}
onGridSizeChanged(params: GridSizeChangedEvent) {
// get the current grids width
const gridWidth = document.querySelector(".ag-grid-viewport")!.clientWidth;
// keep track of which columns to hide/show
const columnsToShow = [];
const columnsToHide = [];
// iterate over all columns (visible or not) in their current displayed order,
// so that hiding follows the order the user sees rather than the column definition order
let totalColsWidth = 0;
const allColumns = params.api.getAllGridColumns();
for (let i = 0, len = allColumns.length; i < len; i++) {
const column = allColumns[i];
totalColsWidth += column.getMinWidth();
if (totalColsWidth > gridWidth) {
columnsToHide.push(column.getColId());
} else {
columnsToShow.push(column.getColId());
}
}
// show/hide columns based on current grid width
params.api.setColumnsVisible(columnsToShow, true);
params.api.setColumnsVisible(columnsToHide, false);
// wait until columns stopped moving and fill out
// any available space to ensure there are no gaps
window.setTimeout(() => {
params.api.sizeColumnsToFit();
}, 10);
}
onFirstDataRendered(params: FirstDataRenderedEvent) {
params.api.sizeColumnsToFit();
}
onGridReady(params: GridReadyEvent<IOlympicData>) {
this.http
.get<
IOlympicData[]
>("https://www.ag-grid.com/example-assets/olympic-winners.json")
.subscribe((data) => (this.rowData = data));
}
}
import '@angular/compiler';
import { provideHttpClient } from '@angular/common/http';
import { enableProdMode } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
if (new URLSearchParams(window.location.search).get('prod') !== 'false') {
enableProdMode();
}
const app = bootstrapApplication(AppComponent, {
providers: [provideHttpClient()],
});
export interface IOlympicData {
athlete: string,
age: number,
country: string,
year: number,
date: string,
sport: string,
gold: number,
silver: number,
bronze: number,
total: number
} Dynamic Vertical Resizing Copy Link
Sometimes the grid is taller than the rows it contains. You can dynamically set the row heights to fill the available height as the following example shows:
import { Component } from "@angular/core";
import { AgGridAngular } from "ag-grid-angular";
import {
ClientSideRowModelApiModule,
ClientSideRowModelModule,
ColDef,
ColGroupDef,
FirstDataRenderedEvent,
GetRowHeight,
GridApi,
GridOptions,
GridReadyEvent,
GridSizeChangedEvent,
ModuleRegistry,
RenderApiModule,
RowApiModule,
RowHeightParams,
enableDevValidations,
} from "ag-grid-community";
import { getData } from "./data";
if (process.env.NODE_ENV !== "production") {
enableDevValidations();
}
ModuleRegistry.registerModules([
ClientSideRowModelApiModule,
RenderApiModule,
RowApiModule,
ClientSideRowModelModule,
]);
@Component({
selector: "my-app",
standalone: true,
imports: [AgGridAngular],
template: `<ag-grid-angular
style="width: 100%; height: 100%;"
[columnDefs]="columnDefs"
[rowData]="rowData"
[getRowHeight]="getRowHeight"
(firstDataRendered)="onFirstDataRendered($event)"
(gridSizeChanged)="onGridSizeChanged($event)"
(gridReady)="onGridReady($event)"
/> `,
})
export class AppComponent {
columnDefs: ColDef[] = [
{ field: "athlete", width: 140 },
{ field: "age", width: 60 },
{ field: "country", width: 130 },
{ field: "year", width: 70 },
{ field: "date", width: 110 },
{ field: "sport", width: 110 },
{ field: "gold", flex: 1 },
{ field: "silver", flex: 1 },
{ field: "bronze", flex: 1 },
{ field: "total", flex: 1 },
];
rowData: any[] | null = getData();
getRowHeight: GetRowHeight = (params: RowHeightParams) => {
return currentRowHeight;
};
onFirstDataRendered(params: FirstDataRenderedEvent) {
updateRowHeight(params);
}
onGridSizeChanged(params: GridSizeChangedEvent) {
updateRowHeight(params);
}
onGridReady(params: GridReadyEvent) {
minRowHeight = params.api.getSizesForCurrentTheme().rowHeight;
currentRowHeight = minRowHeight;
}
}
let minRowHeight = 25;
let currentRowHeight: number;
const updateRowHeight = (params: { api: GridApi }) => {
// get the height of the grid body - this excludes the height of the headers
const gridViewport = document.querySelector<HTMLElement>(".ag-grid-viewport");
const topRows = document.querySelector<HTMLElement>(
".ag-grid-pinned-top-rows",
);
const bottomRows = document.querySelector<HTMLElement>(
".ag-grid-pinned-bottom-rows",
);
if (!gridViewport) {
return;
}
const gridHeight =
gridViewport.clientHeight -
(topRows?.clientHeight ?? 0) -
(bottomRows?.clientHeight ?? 0);
// get the rendered rows
const renderedRowCount = params.api.getDisplayedRowCount();
if (renderedRowCount === 0) {
return;
}
// if the rendered rows * min height is greater than available height, just set the height
// to the min and let the scrollbar do its thing
if (renderedRowCount * minRowHeight >= gridHeight) {
if (currentRowHeight !== minRowHeight) {
currentRowHeight = minRowHeight;
params.api.resetRowHeights();
}
} else {
// set the height of the row to the grid height / number of rows available
currentRowHeight = Math.floor(gridHeight / renderedRowCount);
params.api.resetRowHeights();
}
};
export function getData(): any[] {
return [
{
athlete: 'Michael Phelps',
age: 27,
country: 'United States',
year: 2012,
date: '12/08/2012',
sport: 'Swimming',
gold: 4,
silver: 2,
bronze: 0,
total: 6,
},
{
athlete: 'Natalie Coughlin',
age: 25,
country: 'United States',
year: 2008,
date: '24/08/2008',
sport: 'Swimming',
gold: 1,
silver: 2,
bronze: 3,
total: 6,
},
{
athlete: 'Aleksey Nemov',
age: 24,
country: 'Russia',
year: 2000,
date: '01/10/2000',
sport: 'Gymnastics',
gold: 2,
silver: 1,
bronze: 3,
total: 6,
},
{
athlete: 'Alicia Coutts',
age: 24,
country: 'Australia',
year: 2012,
date: '12/08/2012',
sport: 'Swimming',
gold: 1,
silver: 3,
bronze: 1,
total: 5,
},
{
athlete: 'Missy Franklin',
age: 17,
country: 'United States',
year: 2012,
date: '12/08/2012',
sport: 'Swimming',
gold: 4,
silver: 0,
bronze: 1,
total: 5,
},
];
}
import '@angular/compiler';
import { provideHttpClient } from '@angular/common/http';
import { enableProdMode } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
if (new URLSearchParams(window.location.search).get('prod') !== 'false') {
enableProdMode();
}
const app = bootstrapApplication(AppComponent, {
providers: [provideHttpClient()],
});
Auto Height Layout Copy Link
Depending on your scenario, you may wish for the grid to auto-size it's height to the number of rows displayed inside the grid. This is useful if you have relatively few rows and don't want empty space between the last row and the bottom of the grid.
To allow the grid to auto-size its height to fit rows, set grid property domLayout='autoHeight'.
When domLayout='autoHeight' then your application should not set height on the grid div, as the div should be allowed flow naturally to fit the grid contents. When auto height is off then your application should set height on the grid div, as the grid will fill the div you provide it.
If using Grid Auto Height, then the grid will render all rows into the DOM. This is different to normal operation where the grid will only render rows that are visible inside the grid's scrollable viewport. For large grids (eg >1,000 rows) the draw time of the grid will be slow, or for very large grids, your application can freeze. This is not a problem with the grid, it is a limitation on browsers on how much data they can easily display on one web page. For this reason, if showing large amounts of data, it is not advisable to use Grid Auto Height. Instead use the grid as normal and the grid's row virtualisation will take care of this problem for you.
The example below demonstrates the autoHeight feature. Notice the following:
- As you set different numbers of rows into the grid, the grid will resize its height to just fit the rows.
- As the grid height exceeds the height of the browser, you will need to use the browser vertical scroll to view data (or the iFrames scroll if you are looking at the example embedded below).
- The height will also adjust as you filter, to add and remove rows.
- If you have pinned rows, the grid will size to accommodate the pinned rows.
- Vertical scrolling will not happen, however horizontal scrolling, including pinned columns, will work as normal.
- You can switch the grid into and out of auto-height mode by calling
api.setGridOption('domLayout', layout)or by changing the bounddomLayoutproperty.
The following example is best viewed in a new tab, so it is obvious that there are no scroll bars. When viewed inline below, the scroll bars shown are for the containing iframe, not the grid.
import { Component } from "@angular/core";
import { AgGridAngular } from "ag-grid-angular";
import "./style.css";
import {
ClientSideRowModelModule,
ColDef,
ColGroupDef,
DomLayoutType,
GridApi,
GridOptions,
GridReadyEvent,
ModuleRegistry,
NumberFilterModule,
PinnedRowModule,
TextFilterModule,
enableDevValidations,
} from "ag-grid-community";
import {
ColumnMenuModule,
ColumnsToolPanelModule,
ContextMenuModule,
RowGroupingModule,
} from "ag-grid-enterprise";
if (process.env.NODE_ENV !== "production") {
enableDevValidations();
}
ModuleRegistry.registerModules([
TextFilterModule,
PinnedRowModule,
ClientSideRowModelModule,
ColumnsToolPanelModule,
ColumnMenuModule,
ContextMenuModule,
RowGroupingModule,
NumberFilterModule,
]);
@Component({
selector: "my-app",
standalone: true,
imports: [AgGridAngular],
template: `<div class="test-header">
<div>
<button (click)="updateRowData(0)">0 Rows</button>
<button (click)="updateRowData(5)">5 Rows</button>
<button (click)="updateRowData(50)">50 Rows</button>
</div>
<div>
<button (click)="setDomLayoutAutoHeight()">Auto Height</button>
<button (click)="setDomLayoutNormal()">Fixed Height</button>
</div>
<div>
<input
name="pinned-rows"
type="checkbox"
id="floating-rows"
(click)="toggleFloatingRows()"
/>
<label for="pinned-rows"> Pinned Rows </label>
</div>
<div>Row Count = <span id="currentRowCount"></span></div>
</div>
<ag-grid-angular
id="myGrid"
[columnDefs]="columnDefs"
[defaultColDef]="defaultColDef"
[rowData]="rowData"
[domLayout]="domLayout"
[popupParent]="popupParent"
(gridReady)="onGridReady($event)"
/>
<div style="border: 10px solid #eee; padding: 10px; margin-top: 20px">
<p style="text-align: center">
This text is under the grid and should move up and down as the height of
the grid changes.
</p>
</div> `,
})
export class AppComponent {
private gridApi!: GridApi;
columnDefs: (ColDef | ColGroupDef)[] = [
{
headerName: "Core",
children: [
{ headerName: "ID", field: "id" },
{ field: "make" },
{ field: "price", filter: "agNumberColumnFilter" },
],
},
{
headerName: "Extra",
children: [
{ field: "val1", filter: "agNumberColumnFilter" },
{ field: "val2", filter: "agNumberColumnFilter" },
{ field: "val3", filter: "agNumberColumnFilter" },
{ field: "val4", filter: "agNumberColumnFilter" },
{ field: "val5", filter: "agNumberColumnFilter" },
{ field: "val6", filter: "agNumberColumnFilter" },
{ field: "val7", filter: "agNumberColumnFilter" },
{ field: "val8", filter: "agNumberColumnFilter" },
{ field: "val9", filter: "agNumberColumnFilter" },
{ field: "val10", filter: "agNumberColumnFilter" },
],
},
];
defaultColDef: ColDef = {
enableRowGroup: true,
enableValue: true,
filter: true,
};
rowData: any[] | null = getData(5);
domLayout: DomLayoutType = "autoHeight";
popupParent: HTMLElement | null = document.body;
updateRowData(rowCount: number) {
this.gridApi.setGridOption("rowData", getData(rowCount));
document.querySelector("#currentRowCount")!.textContent = `${rowCount}`;
}
toggleFloatingRows() {
const show = (document.getElementById("floating-rows") as HTMLInputElement)
.checked;
if (show) {
this.gridApi.setGridOption("pinnedTopRowData", [
createRow(999),
createRow(998),
]);
this.gridApi.setGridOption("pinnedBottomRowData", [
createRow(997),
createRow(996),
]);
} else {
this.gridApi.setGridOption("pinnedTopRowData", undefined);
this.gridApi.setGridOption("pinnedBottomRowData", undefined);
}
}
setDomLayoutAutoHeight() {
this.gridApi.setGridOption("domLayout", "autoHeight");
// auto height will get the grid to fill the height of the contents,
// so the grid div should have no height set, the height is dynamic.
(document.querySelector<HTMLElement>("#myGrid")! as any).style.height = "";
}
setDomLayoutNormal() {
this.gridApi.setGridOption("domLayout", "normal");
// when auto height is off, the grid has a fixed height and provides
// scrollbars if the data does not fit into it.
(document.querySelector<HTMLElement>("#myGrid")! as any)!.style.height =
"400px";
}
onGridReady(params: GridReadyEvent) {
this.gridApi = params.api;
document.querySelector("#currentRowCount")!.textContent = "5";
}
}
function createRow(index: number) {
const makes = ["Toyota", "Ford", "BMW", "Phantom", "Porsche"];
return {
id: "D" + (1000 + index),
make: makes[Math.floor(window.agRandom() * makes.length)],
price: Math.floor(window.agRandom() * 100000),
val1: Math.floor(window.agRandom() * 1000),
val2: Math.floor(window.agRandom() * 1000),
val3: Math.floor(window.agRandom() * 1000),
val4: Math.floor(window.agRandom() * 1000),
val5: Math.floor(window.agRandom() * 1000),
val6: Math.floor(window.agRandom() * 1000),
val7: Math.floor(window.agRandom() * 1000),
val8: Math.floor(window.agRandom() * 1000),
val9: Math.floor(window.agRandom() * 1000),
val10: Math.floor(window.agRandom() * 1000),
};
}
function getData(count: number) {
const rowData = [];
for (let i = 0; i < count; i++) {
rowData.push(createRow(i));
}
return rowData;
}
/* Manually set dark mode to get a dark scroll bar on the body */
html[data-color-scheme='dark'] body {
color-scheme: dark;
}
.test-header {
display: flex;
justify-content: space-between;
padding: 5px;
font-size: 13px;
margin-bottom: 1rem;
}
.test-header > div {
vertical-align: middle;
align-content: center;
}
.test-header button {
margin-right: 5px;
margin-bottom: 0;
margin-top: 0;
}
.test-header input {
margin-top: 0;
margin-bottom: 0;
}
.test-header #floating-rows {
vertical-align: bottom;
}
.ag-grid-pinned-top-rows-container .ag-row {
background-color: #2244cc44;
}
.ag-grid-pinned-bottom-rows-container .ag-row {
background-color: #2244cc44;
}
import '@angular/compiler';
import { provideHttpClient } from '@angular/common/http';
import { enableProdMode } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
if (new URLSearchParams(window.location.search).get('prod') !== 'false') {
enableProdMode();
}
const app = bootstrapApplication(AppComponent, {
providers: [provideHttpClient()],
});
Min Height with Auto Height Copy Link
When using Auto Height, the grid rows section has a minimum height of 150px. This is to avoid a zero-height grid which looks weird.
Use the autoHeightMinBodyHeight theme parameter to change this minimum:
const myTheme = themeQuartz.withParams({
autoHeightMinBodyHeight: 40,
});It is not possible to specify a max height when using auto-height.
Users ask is it possible to set a max height when using auto-height? The answer is no. If using auto-height, the grid is set up to work in a different way. It is not possible to switch. If you do need to switch, you will need to turn auto-height off.
Print Layout Copy Link
For details on displaying the grid in a printer friendly layout see the Print Layout page.