在 material 手风琴中重新加载数据源后保持展开的行状态

Keep expanded row state after reloading data source in material accordion

我有一个带嵌套扩展面板的手风琴,我想在重新加载数据后保持每行的 expanded/not 扩展状态。

我在可用于扩展面板的扩展输入中的 material 手风琴文档中找到了它,但我没有看到保持每一行状态以便将其传递给扩展输入。 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>

如果您跟踪扩展的地区和国家会怎么样?

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

mat-expansion-panel 组件的 openedclosed 输出添加一些事件处理程序并相应地更新地图:

<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>

handlers无非就是这样:

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

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

无论何时重新加载数据,之前展开的面板都应保持其状态。如果你刷新页面,这当然会丢失,如果你需要跨页面刷新持久化,查看会话存储或本地存储并将它们放在那里。