Keep expanded row state after reloading data source in material accordion

Issue

I have an accordion with nested expansion panels and I want to keep the expanded/not expanded status of each row after data is reloaded.

I found on the documentation of material accordion in expanded input that can be used for expansion panels, but I don’t see a solution to keep the state of each row in order to pass it to the expanded input. https://material.angular.io/components/expansion/api

        <mat-expansion-panel *ngFor="let region of (groupedData | keyvalue)">
            <mat-expansion-panel *ngFor="let country of (region.value | keyvalue)"
              togglePosition='before'>
            </mat-expansion-panel>
        </mat-expansion-panel>

Solution

What if you keep track of the expanded regions and countries?

expandedRegions: { [key: string]: boolean } = {};
expandedCountries: { [key: string]: boolean } = {};

Add some event handlers for the opened and closed outputs of the mat-expansion-panel component and update the maps accordingly:

<mat-expansion-panel *ngFor="let region of (groupedData | keyvalue: regionSortFn)"
  (opened)="handleRegionPanelStateChange(region.key, true)"
  (closed)="handleRegionPanelStateChange(region.key, false)"
  [expanded]="expandedRegions[region.key]">
  <!-- ... -->
  <mat-expansion-panel *ngFor="let country of (region.value | keyvalue: countrySortFn)"
    togglePosition='before'
    (opened)="handleCountryPanelStateChanged(country.key, true)"
    (closed)="handleCountryPanelStateChanged(country.key, false)"
    [expanded]="expandedCountries[country.key]">
    <!-- ... -->
  </mat-expansion-panel>
</mat-expansion-panel>

The handlers are nothing more than this:

handleRegionPanelStateChange(key: string, isOpen: boolean) {
  this.expandedRegions = { ...this.expandedRegions, [key]: isOpen };
}

handleCountryPanelStateChanged(key: string, isOpen: boolean) {
  this.expandedCountries = { ...this.expandedCountries, [key]: isOpen };
}

Whenever you reload the data, the panels that were previously expanded should keep their state. If you refresh the page, this will of course be lost, if you need to persist across page refreshes, look into session storage or local storage and put them there.

Answered By – Octavian Mărculescu

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published