How do I get and set ag-grid state?

独自空忆成欢 提交于 2019-12-18 11:48:48

问题


How can I obtain and re-set the state of an ag-grid table? I mean, which columns are being show, in what order, with what sorting and filtering, etc.

Update: getColumnState and setColumnState seem to be close to what I want, but I cannot figure out the callbacks in which I should save and restore the state. I tried restoring it in onGridReady but when the actual rows are loaded, I lose the state.


回答1:


I believe you are looking for this page of the Docs. This describes the column api and what functions are available to you. The functions that are of most relevance would be:

  • getAllDisplayedColumns() - used to show what columns are able to be rendered into the display. Due to virtualization there may be some columns that aren't rendered to the DOM quite yet, iff you want only the columns rendered to the DOM then use getAllDisplayedVirtualColumns() - both functions show the order as they will be displayed on the webpage
    • The Column object that is returned from these functions contains sort and filter attributes for each of the columns.

I believe that all you need would be available to you from that function which would be called like this gridOptions.columnApi.getAllDisplayedColumns()

Other functions which might be useful:

  • Available from gridOptions.columnApi:
    • getColumnState() - returns objects with less detail than the above funciton - only has: aggFunc, colId, hide, pinned, pivotIndex, rowGroupIndex and width
    • setColumnState(columnState) - this allows you to set columns to hidden, visible or pinned, columnState should be what is returned from getColumnState()
  • Available from gridOptions.api:
    • getSortModel() - gets the current sort model
    • setSortModel(model) - set the sort model of the grid, model should be the same format as is returned from getSortModel()
    • getFilterModel() - gets the current filter model
    • setFilterModel(model) - set the filter model of the grid, model should be the same format as is returned from getFilterModel()

There are other functions that are more specific, if you only want to mess with pinning a column you can use setColumnPinned or for multiple columns at once use setColumnsPinned and more functions are available from the linked pages of the AG-Grid docs




回答2:


The gridReady event should do what you need it to do. What I suspect is happening is your filter state is being reset when you update the grid with data - you can alter this behaviour by setting filterParams: {newRowsAction: 'keep'}

This can either by set by column, or set globally with defaultColDef.

Here is a sample configuration that should work for you:

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'}
    }
};

I've created a plunker here that illustrates how this would work (note I'm restoring state from hard code strings, but the same principle applies): https://plnkr.co/edit/YRH8uQapFU1l37NAjJ9B . The rowData is set on a timeout 1second after loading




回答3:


There is a very specific example on their website providing details for what you are trying to do: 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');
}

and for restoring:

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');
}



回答4:


The following needs to be done.

Include a div for the grid in your html

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

On the js side

//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);

Check this pen out for more features. https://codepen.io/mrtony/pen/PPyNaB . Its done with angular




回答5:


To keep the filter values you may use filterParams: {newRowsAction: 'keep'}




回答6:


Step 1 :

First of all, you need to add dependencies to your project. In your package.json, add the following code :

"dependencies": {
 ...
 "ag-grid": "6.1.0",
 "ag-grid-ng2": "6.1.0"
 }

Make sure to have the latest version of ag-Grid.

Step 2 :

Update System.config.js to use ag-grid in your project.

System.config({
 packages: {
  ...
  'ag-grid-ng2': {
    defaultExtension: "js"
   },
  'ag-grid': {
    defaultExtension: "js"
  }
 },
 map: {
  ...
  'ag-grid-ng2': 'node_modules/ag-grid-ng2',
  'ag-grid': 'node_modules/ag-grid'
 }
});

Step 3 :

Import AgGridModule in the Module where you want to use it.

import {AgGridModule} from 'ag-grid-ng2/main';

@NgModule({
 imports: [
 BrowserModule,
 AgGridModule.forRoot(),
 ...
})

forRoot part is to ensure that the providers of AgGrid are injected at the root level.

Step 4:

And, the last thing is to include the CSS for ag-Grid. You can do it directly in your index.html

<link href="node_modules/ag-grid/dist/styles/ag-grid.css" rel="stylesheet" />
<link href="node_modules/ag-grid/dist/styles/theme-material.css" rel="stylesheet" />

That’s it. The setup is complete.

Let’s move on to the implementation

Create a component where you want to use your grid.

@Component({
 selector: 'ag-grid',
 template: `
 <ag-grid-ng2 style="width: 80%; margin-left: 10%" #agGrid class="ag-material"
  [gridOptions]="myGridOptions">
 </ag-grid-ng2>`
})

**export class MyGridComponent{ }**

In the template, we have tag. This is provided by the AgGridModule we imported before. The thing to notice is the “gridOptions” property, we have assigned it to a variable named “myGridOptions”, and therefore we need to initialize that variable in the component. Add the following code in the component :

 private myGridOptions: GridOptions = {};

This initializes an empty grid. Now, obviously, we need some data in our grid.

To add date to an ag-Grid, we have two properties of GridOptions:

rowData
columnDefs

we can initialize both of them on ngOninit. Import OnInit and implement it to the component, and add the following code :

import { OnInit } from '@angular/core';

export class MyGridComponent implements OnInit{

ngOnInit() {
 this.myGridOptions.rowData = this.createRowData();
 this.myGridOptions.columnDefs = this.createColumnDefs();
}

private createColumnDefs() {
 return [
  {headerName: "NAME", field: "name", width: 100}, 
  {headerName: "AGE", field: "age", width: 100},
  {headerName: "GENDER", field: "gender", width: 100}
  ]
}

//data gets mapped to the corresponding "field" key of the headers

private createRowData() {          
 return [
  {name: "Geller", age: 30, gender: "Male"},
  {name: "Geller", age: 28, gender: "Female"},
  {name: "Tribbiani", age: 29, gender: "Male"},
  {name: "Bing", age: 30, gender: "Male"},
  {name: "Green", age: 28, gender: "Female"},
  {name: "Buffay", age: 29, gender: "Female"}
  ];
 }
}

Here we have two methods that add the headers and row data into the grid.

This is how your grid should look like :

blog1_1

We are using the material theme, but you can choose whichever one you like from here.

Now, in a general scenario, you’ll be getting this data from a service. Let’s create a mock service for that. But before doing that, we should create a type for our data.

Create a file “friends.ts”, and create a class Friends as follows :

export class Friends{
  name: string;
  age: number;
  gender: string;
}

Now, for the mock service, create a file friends.service.ts, and add the following code :

import {Friends} from "./friends";
export class FriendsService{

  getDate() {
    let friends: Friends[] = [
      {name: "Geller", age: 30, gender: "Male"},
      {name: "Geller", age: 28, gender: "Female"},
      {name: "Tribbiani", age: 29, gender: "Male"},
      {name: "Bing", age: 30, gender: "Male"},
      {name: "Green", age: 28, gender: "Female"},
      {name: "Buffay", age: 29, gender: "Female"},
    ];
    return friends
  }
}

To use the service, add it to the providers section of your ngModule.

Now, we need to update our methods in the component. Rows will directly get mapped, because rowData property needs an array of any type, so all we need to do is update the createColumnDefs method.

constructor(private friendsService: FriendsService){}

ngOnInit() {
 let data: Friends[] = this.friendsService.getDate();
 this.myGridOptions.rowData = data;
 this.myGridOptions.columnDefs = this.createColumnDefs(data[0]);
}

private createColumnDefs(friends: Friends) {
 let keyNames = Object.keys(friends);
 let headers = [];
 keyNames.map(key => {
 headers.push({
 headerName: key.toUpperCase(),
 field: key,
 width: 100
 })
 });

 return headers;
}

We simply extract the keys from the data, add properties like width and field, and push it into an array.



来源:https://stackoverflow.com/questions/42811020/how-do-i-get-and-set-ag-grid-state

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!