Ag-grid has a sizeColumnsToFit function that sizes the columns to fit the screen, but what I want is to size the columns to fit the data. In other words I want each column's width to be the minimum required to fit its content (without truncating strings and adding ellipses) even if that means I have to scroll horizontally to see some of the columns.
The autoSizeColumns function seems to be making all the columns equal width, disregarding the width of the contents.
You can see both of these functions in the "Resizing Example" demo on this page.
For the "size to fit" option you can see truncated strings in some columns, but not the first column, presumably because it has "suppressSizeToFit: true". But adding that option to all column defs doesn't solve the problem; there's still some truncation in some columns, while others are wider than they need to be for the content.
Here's the code from that example:
const columnDefs = [
{ field: 'athlete', width: 150, suppressSizeToFit: true },
{
field: 'age',
headerName: 'Age of Athlete',
width: 90,
minWidth: 50,
maxWidth: 150,
},
{ field: 'country', width: 120 },
{ field: 'year', width: 90 },
{ field: 'date', width: 110 },
{ field: 'sport', width: 110 },
{ field: 'gold', width: 100 },
{ field: 'silver', width: 100 },
{ field: 'bronze', width: 100 },
{ field: 'total', width: 100 },
];
const gridOptions = {
defaultColDef: {
resizable: true,
},
columnDefs: columnDefs,
rowData: null,
onColumnResized: (params) => {
console.log(params);
},
};
function sizeToFit() {
gridOptions.api.sizeColumnsToFit();
}
function autoSizeAll(skipHeader) {
const allColumnIds = [];
gridOptions.columnApi.getAllColumns().forEach((column) => {
allColumnIds.push(column.getId());
});
gridOptions.columnApi.autoSizeColumns(allColumnIds, skipHeader);
}
// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', () => {
const gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
fetch('https://www.ag-grid.com/example-assets/olympic-winners.json')
.then((response) => response.json())
.then((data) => gridOptions.api.setRowData(data));
});
Any help?
I'm actually trying to get this working with JustPy using run_api, and I have that (sort of) working, except that the sizeColumnsToFit function doesn't do what I expected.
Most columns of my data consist of fixed-width strings (different widths, but the same width for all strings in a column), so I guess my "plan B" is to commit to a monospace font and font size and try to use trial and error to come up with a width calculation formula based on string lengths.
But sizing columns to fit data is a pretty common thing to want (isn't that what autofit does in Excel?), so I'm hoping there's a more robust solution.
I think you'll find autoSizeColumns does what you need it to.
Take a look at this demo.
Related
I know that I can use the flex attribute on a column def if I want that column to take up the remaining space of a grid, like this:
public columnDefs: ColDef[] = [
{ field: 'name', flex: 1 },
{ field: 'medals.gold', headerName: 'Gold' },
{ field: 'person.age' },
];
And I know that I can pin a column to the left (or right) so that it doesn't scroll with the rest of the columns:
public columnDefs: ColDef[] = [
{ field: 'name', pinned: 'left' },
{ field: 'medals.gold', headerName: 'Gold' },
{ field: 'person.age' },
];
But I have a case where I want the first column to both be pinned AND fill the remaining space:
public columnDefs: ColDef[] = [
{ field: 'name', flex: 1, pinned: 'left' },
{ field: 'medals.gold', headerName: 'Gold' },
{ field: 'person.age' },
];
And when I do this (pinned + flex) the grid seems to ignore the flex attribute and always renders the column with the default width. I've been through the AG-Grid docs and don't see anything that explicitly says pinning and flex columns are incompatible, but maybe I'm missing it.
Here's a plunker to play with. Try removing the pinned attribute to see the flex column work.
Has anyone been able to combine these attributes on one column?
OK, I've found a solution. I'm not sure if this is a workaround, or if this is the way you're supposed to do it, so...
It was a combination of handling the gridReady event and calling Grid API api.sizeColumnsToFit().
In my case, I also set the width and suppressSizeToFit=true for the non-pinned columns.
Updated plunker.
Does anybody have experience with configuring the autoGroupColumnDef property for AG Grid? I am simply trying to make the default Group Column for my treeData grid to only show the expand/collapse chevron (with no group text). Below is my autoGroupColumnDef config and the current visual state:
const gridOptions: GridOptions = {
treeData: true,
getDataPath: (data) => data.hierarchy as string[],
autoGroupColumnDef: {
headerName: "",
width: 30, // <-- gets completely ignored??
valueFormatter: () => "",
cellRenderer: "agGroupCellRenderer",
cellRendererParams: {
suppressCount: true,
},
},
}
As you can see, I am left with a large amount of whitespace between the chevron in the group column and the data columns despite my setting an explicit width: 30 in the config. How can I get rid of this whitespace?
Use maxWidth instead of width.
How can you set the columns of a DetailsList to a specific width at mount?k
I wanted to save the column widths every time they are saved and restore them when the component remounts, i.e., revisits the view where the list is.
return [...staticColumns, ...visibleColumns.map(c => {
return {
key: c.Name,
name: c.Title,
fieldName: c.Name,
minWidth: 100,
isResizable: true,
isCollapsible: true,
onRender: (item: any, index: number, column: IColumn) => {
column.minWidth = 20;
return <span>{item[c.Name]}</span>;
},
} as IColumn;
})];
First set initial minWidth: 100, then change to 20 in the onRender callback. It's work for me
Found this. Guess you can't easily.
https://github.com/microsoft/fluentui/issues/9287
Please refer to the image shown below. (The highlighted part is the ROW header that I need in AG-Grid)
I am not sure about the functional use case of this first column for you.
Nevertheless you can achieve this by adding it to column definition as shown below.
var gridOptions = {
// define grid columns
columnDefs: [
// using default ColDef
{
headerName: ' ',
field: '__',
width: 15,
sortable: false,
cellStyle: {
// you can use either came case or dashes, the grid converts to whats needed
backgroundColor: 'lightgrey', // whatever cell color you want
},
},
...
}
Created working sample plnkr here.
As far as I know ag-grid doesn't have any built-in support for row headers, but as a workaround you can make your first column appear as row headers. I recommend making the whole column look a little different compared to the other columns (including the column header if it's not blank) so it can clearly be seen they are column headers, not standard row data.
Example column definitions:
ColumnDefs: [
{ headerName: 'Column Title 1', field: 'Column1', minWidth: 100, headerClass: "upperLeftCell", cellStyle: {
backgroundColor: 'AliceBlue', //make light blue
fontWeight: 'bold' //and bold
}
},
{ headerName: 'Column Title 2', field: 'Column2', minWidth: 100 },
{ headerName: 'Column Title 3', field: 'Column3', minWidth: 100 }
]
You can also style in SCSS as shown here with the upper left cell:
::ng-deep .ag-header-cell.upperLeftCell {
background-color: aliceblue;
font-weight: bold;
}
In your data rows: you have to enter in the first column the title you want for each row.
Add this as your first colDef. It will render a index column that is unmovable. I have a separate IndexColumnCellRender so won't look exact the same, fill in cellStyle to fit your needs, or make a dedicated cell render like me.
const rowIndexColumn: ColDef = {
valueGetter: ({ node }) => {
const rowIndex = node?.rowIndex;
return rowIndex == null ? "" : rowIndex + 1;
},
width: columnWidth,
headerName: "",
colId: "some-id",
field: "some-id",
suppressNavigable: true,
suppressPaste: true,
suppressMovable: true,
suppressAutoSize: true,
suppressMenu: true,
lockPosition: true,
cellStyle: { padding: 0 },
};
Is the following format possible with ag-grid:
Merged header with blank name
Merged header with name in 2 lines ("Original Values")
Parent header centered ("Header with children")
Thank you, for the question I know it is been too late for the answer but just to help another people know it.
Yes, it is possible with an updated version of ag-grid, please check it out.
`var columnDefs = [ {
headerName: 'Athlete Details',
children: [
{
headerName: 'Athlete',
field: 'athlete',
width: 150,
suppressSizeToFit: true,
enableRowGroup: true,
rowGroupIndex: 0,
},
{
headerName: 'Age',
field: 'age',
width: 90,
minwidth: 75,
maxWidth: 100,
enableRowGroup: true,
}
]
}];
`
https://plnkr.co/edit/?p=preview&preview
I'm struggling with this for quite a while, but i can not find a good solution. Anyway i figured out a solution (at least for my self).
In my case, the headers are dynamic. Only some headers have children.
Here is the solution:
Figure out how many rowspan should a header have
Apply class to header
In your columnDefs, use 'headerClass'
const rowSpanClass = ..... // This is calculated base on the data you have or set it static
columnDefs = {
....
....
headerClass: rowSpanClass, // In my case, if it is 2 rowspan, i call it 'header-row-span-2'
......
}
Apply style on the custom header class
.header-row-span-2 {
position: fixed;
top: 50px;
height: 100px;
}
.header-row-span-3 {
position: fixed;
top: 100px;
height: 150px;
}
The value of 'top' and 'height' need to be changed accordingly (ag-grid header height is 50px by default)
Just to share. I think this is not possible using the headers in ag-grid. So, instead, I set the headerheight to 0 and use the row cells to achieve the header format.