Created
November 29, 2023 20:38
-
-
Save JaimeStill/af1d4546666f2f4086887978e6ac1565 to your computer and use it in GitHub Desktop.
Cache MatTabGroup selection with Router QueryParams
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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