Sync material tabs with anchor/hash

By default `MatTabsGroup` opens the first available tab. We can change it via input, but a more elegant way is to create a logic to save the selected tab into a URL (thanks to the anchor) and allow users to send a URL with the already selected tab.

You can view the source code for this project by following this link: GitHub

Demo

To see how the anchor is changing during navigation through tabs open the demo in a new window.

Writing logic to sync a tab with an anchor

We can move all logic related to synchronizing the opened tab with hash to directive. Thanks of that our solution will be very easy to use in other places.

1
@Directive({
2
standalone: true,
3
selector: "[appSyncTabsWithAnchor]",
4
})
5
export class SyncTabsWithAnchor implements AfterContentInit {
6
private group = inject(MatTabGroup, { self: true });
7
private router = inject(Router);
8
9
private activatedRoute = inject(ActivatedRoute);
10
private destroyRef = inject(DestroyRef);
11
12
ngAfterContentInit() {
13
const fragment = this.activatedRoute.snapshot.fragment;
14
15
if (fragment) {
16
const indexByLabel = this.group._tabs.toArray().findIndex((tab) => tab.textLabel === fragment);
17
18
if (indexByLabel !== -1) {
19
this.group.selectedIndex = indexByLabel;
20
} else {
21
this.group.selectedIndex = +fragment.replace("tab-", "") || 0;
22
}
23
}
24
25
const tabChangeSub = this.group.selectedTabChange.subscribe((event) =>
26
this.router.navigate([], {
27
relativeTo: this.activatedRoute,
28
fragment: event.tab.textLabel || "tab-" + event.index.toString(),
29
replaceUrl: true,
30
}),
31
);
32
this.destroyRef.onDestroy(() => tabChangeSub.unsubscribe());
33
}
34
}

Take a look at how the directive works. First, the directive checks if a tab has label. If not the directive will create a fake ID with the pattern tab-{index}.

How to use

To use the directive just add the selector to a component.

1
<mat-tab-group appSyncTabsWithAnchor>
2
<mat-tab label="First"> Content 1 </mat-tab>
3
<mat-tab label="Second"> Content 2 </mat-tab>
4
<mat-tab label="Third"> Content 3 </mat-tab>
5
</mat-tab-group>

Do not forget to import the directive to your component/module.

You cannot have more than one mat-tab-group on the page. To get a deal with it you should rewrite logic to save the opened tab in another place (for example in query params).

Do you like the content?

Your support helps me continue my work. Please consider making a donation.

Donations are accepted through PayPal or Stripe. You do not need a account to donate. All major credit cards are accepted.

Leave a comment