handsontable: hide some columns without changing data array/object

renathy picture renathy · Mar 1, 2015 · Viewed 17.4k times · Source

I have a data to show in grid. I am using handsontable to show data. Each 3rd column is computed as difference of previous two (for example, 3rd column is rendered as the sum of 1st and 2nd column; this is done by custom renderer taking sum of i-1 and i-2 columns).

This is my custom renderer for "difference" columns:

var val1 = instance.getDataAtCell(row, col - 1),
    val2 = instance.getDataAtCell(row, col - 2),
    args = arguments;
        args[5] = val2 - val1;
        if (args[5] !== 0) {
            $(td).addClass('grid-column-class-nonzero');
        }
        Handsontable.renderers.NumericRenderer.apply(this, args);

I need to have a "switch". This switch would show/hide columns. If switch is ON then I need to show all columns. If switch is OFF, I need to show only columns that contains differences. So, can you suggest - how to hide columns in hansontable?

EDIT: I have updated my code as suggested by @ZekeDroid.

 // on 'switch click' I modify colsToHide global array and do table re-render
 $('#my-id').handsontable('render');

And this is my custom renderer for columns that should be hidden/shown based on switch:

var colsToHide = [];
var classModel1Renderer = function (instance, td, row, col, prop, value, cellProperties) {
    "use strict";
    if (colsToHide.indexOf(col) > -1) {
        td.hidden = true;
    } else {
        td.hidden = false;
    }

    Handsontable.renderers.TextRenderer.apply(this, arguments);
    $(td).addClass('grid-column-class-model1');
};

This code indeed hides/shows columns, but it doesn't work for header column.

Answer

Sst picture Sst · Nov 4, 2016

You can use colWidths to reduce the width of a specific column to 0.1 pixels. Technically it's still part of the table and .getData() returnes the data of the colum, but to the human eye it's invisible. If you get so many columns, that the 0.1 pixel columns stack up to be visible, you can still add more zeros behind the comma to reduce the columns with again :)

handsontable.updateSettings({
    colWidths: [0.1,0.1,50],
});

This example would "hide" the first two colums and show the third colum with 50 px.

PS. To hide the first column I recommend a width of 1px, so that the column borders of the second column doesn't look incomplete