Angular 8 个带有 Material 个选项卡 - select 重新加载时最后一个活动选项卡

Angular 8 with Material tabs - select last active tab on reload

使用以下示例:

Example

如何在重新加载页面时激活上次选择的选项卡?有设计模式吗?

谢谢

这是一个简单、朴素的硬编码版本:

<mat-tab-group [selectedIndex]="1">
  <mat-tab label="system" routerLink="syspref"> Default Preferences </mat-tab>
  <mat-tab label="user" routerLink="userpref"> User Preferences </mat-tab>
</mat-tab-group>

为了使其更通用,您需要有一些编程方式来了解您有多少个选项卡。例如,如果您从数组构建选项卡。

<mat-tab-group [selectedIndex]="tabs.length - 1">
  <mat-tab *ngFor="let tab of tabs" [label]="tab.label" [routerLink]="tab.link">{{tab.name}}</mat-tab>
</mat-tab-group>

其中 tabs 是具有适当 属性 名称的对象数组。

编辑:

您想在页面重新加载时保留活动选项卡。

我为此遵循的一般模式是:

  1. 在选项卡更改时,将索引添加到查询参数
  2. 页面加载时,在查询参数中查找索引
  3. 如果有效,设置活动标签索引

分量

constructor(private route: ActivatedRoute,
  private router: Router) {}

selectedTabIndex: number;

ngOnInit(): void {
  this.selectedTabIndex = parseInt(this.route.snapshot.queryParamMap.get('tab'), 10);
  // TODO: check upper bound. Material will set the last tab as selected
  // if selectedTabIndex >= number of tabs
  if (isNaN(this.selectedTabIndex) || this.selectedTabIndex < 0) {
    this.selectedTabIndex = 0;
  }
}

onTabChange(selectedTabIndex: number): void {
  this.router.navigate([], { relativeTo: this.route, queryParams: {
    tab: selectedTabIndex
  }});
  this.selectedTabIndex = selectedTabIndex;
}

html

<mat-tab-group [selectedIndex]="selectedTabIndex" 
  (selectedIndexChange)="onTabChange($event)">
  <mat-tab label="system" routerLink="syspref"> Default Preferences </mat-tab>
  <mat-tab label="user" routerLink="userpref"> User Preferences </mat-tab>
</mat-tab-group>

我建议将最后一个 tabIndex 存储在 localStorage 中。

更新 tabIndex 以引用 localStorage 中最后保存的索引。 因此,当页面刷新或返回时,它会显示最后显示的选项卡。