Dev93
Dev93

Reputation: 728

Is there a way to dynamically set the col widths of Angularjs ui-grid?

Is there a way to dynamically, programmatically, change the widths of columns in ui-grid for Angularjs?

I've tried changing $scope.gridOptions.columnDefs[i].width, but it doesn't have any effect.

I ask because I have the ui-grid-resize-columns directive set, allowing the user to resize columns that are originally set as percentage widths. But as soon as the user makes any manual modification, the columns sizes all become static, no longer growing or shrinking with the overall table width.

I'd like to add an "autofit" button that would allow the user to restore the column size definitions to percentages (based on their current manually set proportions) that add up to 100%. Ideally, the columns would then start adjusting to table size changes again.

I can just see the user regularly hitting F5 to get this effect (I would!), unknowingly causing the entire page to reload from scratch, costing significant server resources unnecessarily. I guess one unhappy alternative is to make them static from the beginning, removing this temptation!

Upvotes: 4

Views: 8951

Answers (2)

Nilay Mistry
Nilay Mistry

Reputation: 76

 function SetColumnDynamicWidth() {
        var cols = _.filter($scope.gridOptions.columnDefs, function (c) {
            return c.visible != false;
        });
        var maxWidth = document.documentElement.clientWidth / cols.length;
        for (var i = 0; i < cols.length; i++) {
            cols[i].maxWidth = parseInt(maxWidth);
        }
    }

Remove maxWidth form colDefs if you have set in $scope.gridOptions.columnDefs from all columns. Set width: "*" in column definations.

Same way you can also set for minWidth

This solution is very useful to large resolution screen. you can extend the ui-grid to all the potion of large screen and equally divide all columns width.

You can avoid the following type of ui-grid problems

ui-grid for large screen

Upvotes: 0

Tom
Tom

Reputation: 219

Changing the columnDef width does not work because a GridColumn is already built from the columnDefs and ui-grid only watches the changes to the columnDefs array not the individual columnDef properties. What you can do is set the new column width on the GridColumn object for the column. This works for me.

    $scope.grid.getColumn('my-column').width = $newWidth;
    $scope.grid.refresh();

You can also remove and re-add the columns that have a changed width property as this should trigger the grid to rebuild the GridColumns from the columnDefs although I have not tested this and the former seems easier.

Upvotes: 5

Related Questions