Handsontable, colWidths: function: how to set a column width fitting content?
Asked Answered
A

3

5

My aim is to set the first column's width equal to a certain number and leave other columns' widths untouched. Now I know that setting

colWidths: [myValue]

actually breaks other columns' widths but this seems to be workaroundable using

colWidths: function(index) {
    if(index == 0)
        return myValue;
    return ???
}

but I wonder what should I return in the place of ???? undefined doesn't work (well, it works in the same fashion as colWidths: [myValue] – every other column gets the same default width). How do I get the "width by content" value for this?

Ariel answered 15/7, 2017 at 22:15 Comment(0)
A
5

Use the option manualColumnResize instead of colWidths but the same way as in your question (only defining the first column witdh) :

manualColumnResize: [myValue]

The first column width will be define as your value, the other columns will still be dynamic. (Because of autoColumnSizeObject set to true by default, which is also changed to false when you use colWidths option).

You can find a working example here.

Agnola answered 19/7, 2017 at 14:8 Comment(0)
S
4

I am currently using

modifyColWidth: function(width, col){
  if(width > 300) return 300;
}

Referencing by col number would work as well.

modifyColWidth: function(width, col){
  if(col === 0) return 300;
}

Edit: You would also need this after HandsOnTable have been instantiated, otherwise you cannot set the width beyond 300px.

colWidths = [];
[...Array(hot.countCols()).keys()].map(i => {
  colWidths.push(hot.getColWidth(i));
});

hot.updateSettings({
  modifyColWidth: ()=>{},
  colWidths: colWidths
});
Syconium answered 23/7, 2018 at 21:44 Comment(0)
A
3

Just in case, I'll post another method that I've found (posted at GitHub):

using var autoColumnSize = handsontableInstance.getPlugin('autoColumnSize'); and autoColumnSize.calculateColumnsWidth(index, 0, true); – this one calculates the necessary width for the column index at row 0 and using Math.max is another option. Here's an implementation – without iterating through all the rows and looking for the maximum, but a proof of principle: http://jsfiddle.net/7u1kxjLe/39/

Ariel answered 19/7, 2017 at 23:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.