如何获取和设置ag-grid状态?

问题描述 投票:0回答:8

如何获取并重新设置ag-grid表的状态?我的意思是,正在显示哪些列、以什么顺序、使用什么排序和过滤等等。

Update:getColumnState 和 setColumnState 似乎接近我想要的,但我无法弄清楚应该保存和恢复状态的回调。我尝试在 onGridReady 中恢复它,但是当加载实际行时,我丢失了状态。

javascript ag-grid
8个回答
20
投票

他们的网站上有一个非常具体的示例,提供了您想要执行的操作的详细信息:javascript-grid-column-definitions

function saveState() {
    window.colState = gridOptions.columnApi.getColumnState();
    window.groupState = gridOptions.columnApi.getColumnGroupState();
    window.sortState = gridOptions.api.getSortModel();
    window.filterState = gridOptions.api.getFilterModel();
    console.log('column state saved');
}

以及恢复:

function restoreState() {
    gridOptions.columnApi.setColumnState(window.colState);
    gridOptions.columnApi.setColumnGroupState(window.groupState);
    gridOptions.api.setSortModel(window.sortState);
    gridOptions.api.setFilterModel(window.filterState);
    console.log('column state restored');
}

11
投票

我相信您正在寻找文档的此页。这描述了列 api 以及您可以使用哪些功能。最相关的功能是:

  • getAllDisplayedColumns()
    - 用于显示哪些列能够呈现到显示器中。由于虚拟化,可能有一些列尚未渲染到 DOM,如果您只想将列渲染到 DOM,则使用
    getAllDisplayedVirtualColumns()
    - 这两个函数都会显示它们将在网页上显示的顺序
    • 从这些函数返回的
      Column
      对象包含每列的排序和过滤属性。

我相信您可以从该函数中获得您需要的一切,该函数将像这样调用

gridOptions.columnApi.getAllDisplayedColumns()

其他可能有用的功能:

  • 可从
    gridOptions.columnApi
    获取:
    • getColumnState()
      - 返回比上述函数更少细节的对象 - 仅具有:aggFunc、colId、hide、pinned、pivotIndex、rowGroupIndex 和 width
    • setColumnState(columnState)
      - 这允许您将列设置为隐藏、可见或固定,
      columnState
      应该是从
      getColumnState()
    • 返回的内容
  • 可从
    gridOptions.api
    获取:
    • getSortModel()
      - 获取当前排序模型
    • setSortModel(model)
      - 设置网格的排序模型,
      model
      应与从
      getSortModel()
    • 返回的格式相同
    • getFilterModel()
      - 获取当前过滤器型号
    • setFilterModel(model)
      - 设置网格的过滤器模型,
      model
      应与从
      getFilterModel()
    • 返回的格式相同

还有其他更具体的功能,如果您只想固定一列,您可以使用

setColumnPinned
或同时使用
setColumnsPinned
多列,并且可以从 AG-Grid 的链接页面获得更多功能文档


7
投票

gridReady
事件应该执行您需要它执行的操作。我怀疑正在发生的事情是,当您使用数据更新网格时,您的过滤器状态正在重置 - 您可以通过设置
filterParams: {newRowsAction: 'keep'}

来更改此行为

这可以按列设置,也可以使用

defaultColDef
进行全局设置。

这是一个适合您的示例配置:

var gridOptions = {
    columnDefs: columnDefs,
    enableSorting: true,
    enableFilter: true,
    onGridReady: function () {
        gridOptions.api.setFilterModel(filterState);
        gridOptions.columnApi.setColumnState(colState);
        gridOptions.api.setSortModel(sortState);
    },
    defaultColDef: {
        filterParams: {newRowsAction: 'keep'}
    }
};

我在这里创建了一个plunker来说明这是如何工作的(注意我正在从硬代码字符串恢复状态,但同样的原则适用):https://plnkr.co/edit/YRH8uQapFU1l37NAjJ9B

rowData
设置为加载后 1 秒超时


1
投票

要保留您可能使用的过滤器值 filterParams:{newRowsAction:'保留'}


1
投票

这是我的方法。它只涉及使用与实例化 agGrid 相同的 API 创建一个包装函数。

此功能中一些有趣的事情

  • 保存/加载到本地存储
  • 利用
    addEventListener
    ,一旦将
    options
    对象传递给
    Grid
    函数,该对象就变得可用。
  • 附加到
    onGridReady
    对象的
    options
    回调,而不删除可能已定义的内容。

用途:

newAgGrid(document.getElementById('my-grid'), options);
    
static newAgGrid(element, options) {
    const ls = window.localStorage;
    const key = `${location.pathname}/${element.id}`;
    const colStateKey = `${key}colstate`;
    const sortStateKey = `${key}sortState`;
    function saveState(params) {
        if (ls) {
            ls.setItem(colStateKey, JSON.stringify(params.columnApi.getColumnState()));
            ls.setItem(sortStateKey, JSON.stringify(params.api.getSortModel()));
        }
    }
    function restoreState(params) {
        if (ls) {
            const colState = ls.getItem(colStateKey);
            if (colState) {
                params.columnApi.setColumnState(JSON.parse(colState));
            }
            const sortState = ls.getItem(sortStateKey)
            if (sortState) {
                params.api.setSortModel(JSON.parse(sortState));
            }
        }
    }
    // monitor the onGridReady event.  do not blow away an existing handler
    let existingGridReady = undefined;
    if (options.onGridReady) {
        existingGridReady = options.onGridReady;
    }
    options.onGridReady = function (params) {
        if (existingGridReady) {
            existingGridReady(params);
        }
        restoreState(params);
    }
    // construct grid
    const grid = new agGrid.Grid(element, options);
    // now that grid is created, add in additional event listeners
    options.api.addEventListener("sortChanged", function (params) {
        saveState(params);
    });
    options.api.addEventListener("columnResized", function (params) {
        saveState(params);
    });
    options.api.addEventListener("columnMoved", function (params) {
        saveState(params);
    });
    return grid;
}

0
投票

我们可以使用

useRef()
来引用
<AgGridReact>
元素,通过以下方式访问 getColumn 和 setColumn 状态。

const GridRef = useRef()

GridRef.current.columnApi.getColumnState() //  get Column state value
GridRef.current.columnApi.setColumnState() //  set Column state value

<AgGridReact
   enableFilter={true}
   rowStyle={rowStyle}
   ref={GridRef}
></AgGridReact>

0
投票

从 AG Grid v31 开始,它现在支持通过单个组合对象加载/保存网格状态。请参阅其变更日志中的 AG-1535 功能 https://ag-grid.com/changelog/

参考:https://ag-grid.com/javascript-data-grid/grid-state

获取任何更改的状态:

function onStateUpdated(event: StateUpdatedEvent<IOlympicData>): void {
  console.log("State updated", event.state);
}

在网格被破坏之前获取状态:

function onGridPreDestroyed(event: GridPreDestroyedEvent<IOlympicData>): void {
  console.log("Grid state on destroy (can be persisted)", event.state);
}

设置初始状态:

const gridOptions: GridOptions<IOlympicData> = {
  initialState: {}, // <=== Set initial state here
  onGridPreDestroyed: onGridPreDestroyed,
  onStateUpdated: onStateUpdated,
};

-2
投票

需要完成以下工作。

在 html 中包含网格的 div

<div id="myGrid" style="width: 500px; height: 200px;"></div>

在js方面

//initialize your grid object
var gridDiv = document.querySelector('#myGrid');



//Define the columns options and the data that needs to be shown
        var gridOptions = {
            columnDefs: [
                {headerName: 'Name', field: 'name'},
                {headerName: 'Role', field: 'role'}
            ],
            rowData: [
                {name: 'Niall', role: 'Developer'},
                {name: 'Eamon', role: 'Manager'},
                {name: 'Brian', role: 'Musician'},
                {name: 'Kevin', role: 'Manager'}
            ]
        };

//Set these up with your grid
        new agGrid.Grid(gridDiv, gridOptions);

查看这支笔的更多功能。 https://codepen.io/mrtony/pen/PPyNaB。它是用 Angular 完成的

© www.soinside.com 2019 - 2024. All rights reserved.