Javascript 如何在 AngularJS ui-grid 中自动调整列宽

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30383871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:06:30  来源:igfitidea点击:

How to auto size column width in AngularJS ui-grid

javascriptangularjsangularjs-directiveangular-ui-grid

提问by Tony

In AngularJS ui-grid, how can I configure the grid so that it can auto adjust the width of the columns according to the contents when it render?

在 AngularJS ui-grid 中,如何配置网格以便它在呈现时可以根据内容自动调整列的宽度?

I know there is a tutorialshowing the auto size function, but that works only when you double click the column, I wish it could happen when the grid is initiated.

我知道有一个教程显示了自动调整大小功能,但只有当你双击列时才有效,我希望它可以在网格启动时发生。

回答by Kathir

I dont think this feature exists at this point. The uiGridColumnResizer directive is registering event listeners on dblclick, mousedown and mouseup. The dblclick event is basically going thru all the rendered cells and calculating the maximum width and setting it as the column width. This will be a performance issue if you have a lot of rows rendered.

我认为此时不存在此功能。uiGridColumnResizer 指令在 dblclick、mousedown 和 mouseup 上注册事件侦听器。dblclick 事件基本上是遍历所有呈现的单元格并计算最大宽度并将其设置为列宽。如果您渲染了很多行,这将是一个性能问题。

I would probably just set a maximum possible width based on the data the grid will have.

我可能只是根据网格将拥有的数据设置最大可能的宽度。

Or try to replicate the behaviour in the uiGridColumnResizer.

或者尝试复制 uiGridColumnResizer 中的行为。

 $elm.on('dblclick', function(event, args) {
      event.stopPropagation();

      var col = uiGridResizeColumnsService.findTargetCol($scope.col, $scope.position, rtlMultiplier);

      // Don't resize if it's disabled on this column
      if (col.colDef.enableColumnResizing === false) {
        return;
      }

      // Go through the rendered rows and find out the max size for the data in this column
      var maxWidth = 0;
      var xDiff = 0;

      // Get the parent render container element
      var renderContainerElm = gridUtil.closestElm($elm, '.ui-grid-render-container');

      // Get the cell contents so we measure correctly. For the header cell we have to account for the sort icon and the menu buttons, if present
      var cells = renderContainerElm.querySelectorAll('.' + uiGridConstants.COL_CLASS_PREFIX + col.uid + ' .ui-grid-cell-contents');
      Array.prototype.forEach.call(cells, function (cell) {
          // Get the cell width
          // gridUtil.logDebug('width', gridUtil.elementWidth(cell));

          // Account for the menu button if it exists
          var menuButton;
          if (angular.element(cell).parent().hasClass('ui-grid-header-cell')) {
            menuButton = angular.element(cell).parent()[0].querySelectorAll('.ui-grid-column-menu-button');
          }

          gridUtil.fakeElement(cell, {}, function(newElm) {
            // Make the element float since it's a div and can expand to fill its container
            var e = angular.element(newElm);
            e.attr('style', 'float: left');

            var width = gridUtil.elementWidth(e);

            if (menuButton) {
              var menuButtonWidth = gridUtil.elementWidth(menuButton);
              width = width + menuButtonWidth;
            }

            if (width > maxWidth) {
              maxWidth = width;
              xDiff = maxWidth - width;
            }
          });
        });

      // check we're not outside the allowable bounds for this column
      col.width = constrainWidth(col, maxWidth);

      // All other columns because fixed to their drawn width, if they aren't already
      resizeAroundColumn(col);

      buildColumnsAndRefresh(xDiff);

      uiGridResizeColumnsService.fireColumnSizeChanged(uiGridCtrl.grid, col.colDef, xDiff);
    });

回答by Leonel Thiesen

There is a pluggin that do this: ui-grid-auto-fit-columns

有一个插件可以做到这一点:ui-grid-auto-fit-columns

GitHub: https://github.com/Den-dp/ui-grid-auto-fit-columns

GitHub: https://github.com/Den-dp/ui-grid-auto-fit-columns

Example: http://jsbin.com/tufazaw/edit?js,output

示例:http: //jsbin.com/tufazaw/edit?js,output

Usage:

用法:

<div ui-grid="gridOptions" ui-grid-auto-fit-columns></div>

angular.module('app', ['ui.grid', 'ui.grid.autoFitColumns'])

回答by cramroop

use an asterisk in your column definition:

在列定义中使用星号:

width:"*";

回答by SnailCoil

So, this worked for me when I needed to shrink all columns except for one. I iterate through all columns after the grid is finished loading, and trigger a double click event on the resizer. Not the prettiest, so if anybody else has a better solution, I'd be very happy to hear it!

因此,当我需要缩小除一列之外的所有列时,这对我有用。我在网格加载完成后遍历所有列,并在调整器上触发双击事件。不是最漂亮的,所以如果其他人有更好的解决方案,我会很高兴听到它!

function resizeColumn(uid) {
    // document.querySelector might not be supported; if you have jQuery
    // in your project, it might be wise to use that for selecting this
    // element instead
    var resizer = document.querySelector('.ui-grid-col' + uid + ' .ui-grid-column-resizer.right');
    angular.element(resizer).triggerHandler('dblclick');
}

var gridOptions = {
    ...
    onRegisterApi: function (gridApi) {
        // why $interval instead of $timeout? beats me, I'm not smart enough
        // to figure out why, but $timeout repeated infinitely for me
        $interval(function() {
            var columns = gridApi.grid.columns;
            for(var i = 0; i < columns.length; i++) {
                // your conditional here
                if(columns[i].field !== 'name') {
                    resizeColumn(columns[i].uid)
                }
            }
        }, 0, 1);
    }
}

回答by rtvalluri

Using width : "*", will adjust all the columns in the available view port, which results in columns to get compressed.

使用width : "*", 将调整可用视口中的所有列,从而导致列被压缩。

Specifying minWidth: "somevalue"and width: "*"makes your ui-grid look better

指定minWidth: "somevalue"width: "*"让您的UI电网更好看

回答by yanai edri

you can use *as in the width property - is consider as autoyou can see here

您可以*在 width 属性中使用as - 就像auto在此处看到的那样考虑

回答by Python Boy

I did not find any implementation for this so this is what I've done

我没有找到任何实现,所以这就是我所做的

  1. Iterated through the first 10 records.

  2. Found the max size of data for each column.

  3. Then created a spantag on the fly and wrapped it with that data.

  4. Measured the width of the tag and that would be your approx width required for the column (might need to append some more constant width due to CSS effect etc).

  5. If first 10 records are nullthen do the same process but this time with column header.

  1. 遍历前 10 条记录。

  2. 找到每列的最大数据大小。

  3. 然后动态创建一个span标签并用该数据包装它。

  4. 测量标签的宽度,这将是列所需的大约宽度(由于 CSS 效果等,可能需要附加一些更恒定的宽度)。

  5. 如果前 10 条记录null执行相同的过程,但这次使用列标题。

回答by Rob Sedgwick

Best solution I can come up with is to:

我能想出的最佳解决方案是:

  1. set the grid width to 100%
  2. set the maxWidth: attribute on the columnDefs you don't want to size to some small number
  3. let the grid size itself
  1. 将网格宽度设置为 100%
  2. 在 columnDefs 上设置 maxWidth: 属性,您不想将其大小设置为某个较小的数字
  3. 让网格大小本身

html:

html:

ui-grid="gridOptions" class="myuigrid" ui-ui-grid-resize-columns ui-grid-ui-grid-auto-resize></div>

css:

css:

.myuigrid {
   width: 100%;
 }

js

js

            columnDefs: [
              { name: 'Id', maxWidth:80 },
              { name: 'Name', maxWidth: 280 },
              { name: 'LongName'},
            ],

I know this won't work in every case but a lot of the time most of your columns are more or less fixed and the variable ones which you know in advance are the ones to let resize.

我知道这不会在所有情况下都有效,但是很多时候您的大多数列或多或少都是固定的,而您事先知道的可变列是可以调整大小的列。

回答by lazell

add the following to the gridoptions

将以下内容添加到 gridoptions

                    init: function (gridCtrl, gridScope) {
                        gridScope.$on('ngGridEventData', function () {
                            $timeout(function () {
                                angular.forEach(gridScope.columns, function (col) {
                                    gridCtrl.resizeOnData(col);
                                });
                            });
                        });
                    }

Make sure you have a width of any random number on each column definition

确保在每个列定义上都有任意随机数的宽度

width: 100 

is fine.

很好。

回答by level

I found some issues with width solution. We should use the property 'cellClass' in ui-grid columns object to enable this class.

我发现宽度解决方案存在一些问题。我们应该使用 ui-grid 列对象中的属性“cellClass”来启用这个类。

.ui-grid-cell-contents-auto {
     /* Old Solution */
    /*min-width: max-content !important;*/

    /* New Solution */
    display: grid;
    grid-auto-columns: max-content;

    /* IE Solution */
    display: -ms-grid;
    -ms-grid-columns: max-content;
}

then you should use the property cellClass in ui-grid columns object to enable this class on your grid (something like this):

那么你应该在 ui-grid columns 对象中使用属性 cellClass 来在你的网格上启用这个类(类似这样):

columns: [{ field: 'search_name', displayName: '', cellClass: 'ui-grid-cell-contents-auto'}]

You can refer to nekhaly'sanswer detailed description. https://github.com/angular-ui/ui-grid/issues/3913

您可以参考nekhaly 的回答详细说明。https://github.com/angular-ui/ui-grid/issues/3913