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>
CodePudding user response:
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.