Keep expanded row state after reloading data source in material accordion


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.

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


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)"
  <!-- ... -->
  <mat-expansion-panel *ngFor="let country of (region.value | keyvalue: countrySortFn)"
    (opened)="handleCountryPanelStateChanged(country.key, true)"
    (closed)="handleCountryPanelStateChanged(country.key, false)"
    <!-- ... -->

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