仅使用Ag-grid中的标题上的复选框选择当前页面中的行

时间:2019-12-12 05:44:16

标签: ag-grid ag-grid-angular

我面临的一个与Ag-grid相关的问题是,当我们选中标题中的复选框时,它们会选择所有总记录(分页中的所有页面),我只想选择当前的页面数据,例如:我有10条记录在第1页中,那么他们应该只在网格中选择10条记录。

2 个答案:

答案 0 :(得分:1)

为您的问题创建解决方案,我选择了“自定义组件”,这将有助于定义要在列定义级别使用的自定义标题渲染器。

CustomHeader将负责网格中的复选框显示-帖子末尾的示例中提供了完整的定义:

  CustomHeader.prototype.init = function(params) { ... }

复选框显示在第一列(使用isFirstColumn函数),每次分页更改时都会刷新 或复选框选择(onPaginationChanged onSelectionChanged)。 这是强制性的,因为只有在选中所有行后才需要检查元素。

  

refreshHeader()重绘标题。如果列名更改或其他更改列标题显示方式的信息,则很有用。

  // grid definition
  $scope.gridOptions = {
    ...
    defaultColDef: {
      sortable: true,
      filter: true,
      resize: true,
      checkboxSelection: isFirstColumn
    },
    onPaginationChanged: onPaginationChanged,
    onSelectionChanged: onSelectionChanged
  };

  // events handlers
  function onSelectionChanged(event) {
    this.api.refreshHeader();
  }

  function onPaginationChanged(event) {
    this.api.refreshHeader();
  }

  function isFirstColumn(params) {
    var displayedColumns = params.columnApi.getAllDisplayedColumns();
    var thisIsFirstColumn = displayedColumns[0] === params.column;
    return thisIsFirstColumn;
  }

Working example AngularJs

Working example Angular5

答案 1 :(得分:0)

基于代码的简单解决方案,无需任何自定义组件:

paginationChanged事件监听器附加到onGridReady网格事件:

onGridReady = (params) =>
{
    this.gridApi.addEventListener('paginationChanged', (e) =>
        {
            //Reset rows selection based on current page
            this.resetPaginationSelection(this);
        });
};

用于处理当前页面中可选行的事件处理程序方法:

resetPaginationSelection = (self) =>
{
    //Deselect previously selected rows to reset selection
    self.gridApi.deselectAll();

    //Initialize pagination data
    let paginationSize = self.gridApi.paginationGetPageSize();
    let currentPageNum = self.gridApi.paginationGetCurrentPage();
    let totalRowsCount = self.gridApi.getDisplayedRowCount();

    //Calculate current page row indexes
    let currentPageRowStartIndex = (currentPageNum * paginationSize);
    let currentPageRowLastIndex = (currentPageRowStartIndex + paginationSize);
    if(currentPageRowLastIndex > totalRowsCount) currentPageRowLastIndex = (totalRowsCount);

    for(let i = 0; i < totalRowsCount; i++)
    {
        //Set isRowSelectable=true attribute for current page rows, and false for other page rows
        let isWithinCurrentPage = (i >= currentPageRowStartIndex && i < currentPageRowLastIndex);
        self.gridApi.getDisplayedRowAtIndex(i).setRowSelectable(isWithinCurrentPage);
    }
};