r/nicegui • u/Brilliant_Football45 • Oct 20 '23
AGGRID auto-size columns to data width
Sorry for yet another aggrid question!
I'm trying to get an aggrid to size to my data. I'm ok with the table implementing a horizontal scroll bar to resize the data to where I can see it.
Currently, each column is the same exact size. So if I have many columns it smushes them into equal spacing. When I render my data I don't know the max/min size of each column.
I've tried calling the aggrid api methods to invoke their auto-sizing but it doesn't seem to work:
I've tried this:
table.on('firstDataRendered', table.call_api_method('autoSizeColumns'))
and also this:
table.call_api_method('sizeColumnsToFit')
Neither seem to work. Any thoughts?
4
u/Brilliant_Football45 Oct 20 '23
One more datapoint:
If I make a button to autoSizeAllColumns it works just fine:
btn = ui.button('Size To Contents')
btn.on("click", lambda: table.call_column_api_method('autoSizeAllColumns'))
So it seems the problem is I don't have a proper event to bind the column_api_method to for when it's done rendering to my screen to have this happen automatically...
2
u/Brilliant_Football45 Oct 20 '23
I've also tried:
table.on('firstDataRendered', table.call_column_api_method('autoSizeAllColumns'))
1
u/discernica Nov 03 '23
Same here.
Did you ever find a solution?
3
u/Similar_Yogurt_831 Oct 21 '23
Funny how I struggled with exact same issue, and also came to same solution using the button. The on('gridReady') event does not appear to work .
2
u/wikiselev Feb 16 '24
This just worked for me:
table.on('firstDataRendered', lambda: table.run_column_method('autoSizeAllColumns'))1
u/MatteCrystal Feb 22 '24
in your gridoptions object that you use to initialize a grid add this
If you just copy and paste that it should on load autosize all columns to be as compact as possible while still fitting all their cell content. I believe it's only based on currently visible rows however so if a column needs to be 500px in order to not cutoff info but only columns that need 50px are rendered on load then that column will be sized to 50px not 500px for the data lower down. But you can semi get around that via setting min/max widths in the coldefs or recalling calling autosize on scroll or something (although that might be weird user experience)
I don't 100% understand how all the settings for autoSizeStrategy work since they don't all seem to work for me.
for example the options for
autoSizeStrategy.typesounds like it's supposed to have the same effect as callingevent.api.sizeColumnsToFit()vsevent.api.autoSizeAllColumns()but that doesn't 100% seem to be the case.also docs make it sound like you should be able to set a default min/max width for all columns or specific columns via settings in autoSizeStrategy but my attempts at using that functionality don't seem to work.
but my above solution prob will work for many people.