How To Save Devexpress Grid State In Angular

Hello Friends, In this article, we will learn how to save devexpress grid state in the angular application and how to use DexExtreme DataGrid in angular. If a user sorts and filters data, groups, reorders, resizes columns, and column hide/show, or makes other changes, the component saves these modifications and restores them when a user reloads the page.

To enable state storing, set stateStoring.enabled to true and specify the storageKey and type properties. Depending on the type, the state can be saved to a localStorage or sessionStorage. With localStorage, the state persists across browser sessions; with sessionStorage, it is reset after the current session. This demo uses localStorage.

Alternatively, you can implement the customSave and customLoad functions to save and load the state according to custom logic. In this case, set the type property to “custom”.

Add grid in the src/app.component.html looks like below:

<dx-data-grid  id="gridContainer" [dataSource]="dataSource" [showBorders]="true" [columnAutoWidth]="true" [allowColumnReordering]="true">   
    <dxo-state-storing  [enabled]="true"  type="custom"  [customLoad]="loadState" [customSave]="saveState"> </dxo-state-storing> 
    <dxo-column-chooser [enabled]="true" [allowSearch]="allowSearch">
    </dxo-column-chooser>
    <dxo-paging [pageSize]="50"></dxo-paging>
    <dxi-column dataField="companyName"></dxi-column>
    <dxi-column dataField="city"></dxi-column>
    <dxi-column dataField="state"></dxi-column>
    <dxi-column dataField="phone"></dxi-column>
    <dxi-column dataField="fax"></dxi-column>
</dx-data-grid>

Add customLoad and customSave method in src/app.component.ts looks like below:

sendStorageRequest = (method, data = null) => {
  if (data) {
    localStorage.setItem("lastState", JSON.stringify(data));
  } else {
    let body = localStorage.getItem("lastState");
    return body ? JSON.parse(body) : null;
  }
}

loadState = () => {
  return this.sendStorageRequest("Get");
}

saveState = (state) => {
  this.sendStorageRequest("Put", state);
}

Now, run the application and see the result look like below

I hope this article helps you and you will like it.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories