Skip to content

Instantly share code, notes, and snippets.

@JaimeStill
Created November 29, 2023 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JaimeStill/af1d4546666f2f4086887978e6ac1565 to your computer and use it in GitHub Desktop.
Save JaimeStill/af1d4546666f2f4086887978e6ac1565 to your computer and use it in GitHub Desktop.
Cache MatTabGroup selection with Router QueryParams
<mat-tab-group [animationDuration]="180"
[selectedIndex]="tabIndex"
(selectedIndexChange)="changeTab($event)">
<mat-tab label="One">
Tab One
</mat-tab>
<mat-tab label="Two">
Tab Two
</mat-tab>
<mat-tab label="Three">
Tab Three
</mat-tab>
<mat-tab-group>
import {
ActivatedRoute,
Router
} from '@angular/router';
import { Component } from '@angular/core';
@Component({
selector: 'cached-mat-tab',
templateUrl: 'cached-mat-tab.html'
})
export class CachedMatTab {
tabIndex: number = 0;
constructor(
private route: ActivatedRoute,
private router: Router
) {
route.queryParamMap.subscribe(params => {
if (params.has('tab'))
this.tabIndex = +params.get('tab');
});
}
changeTab(index: number) {
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
tab: index > 0 ? index : null
},
queryParamsHandling: 'merge'
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment