-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpage-title.strategy.ts
More file actions
65 lines (53 loc) · 2.04 KB
/
Copy pathpage-title.strategy.ts
File metadata and controls
65 lines (53 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { Injectable, inject } from '@angular/core';
import { Title } from '@angular/platform-browser';
import {
ActivatedRouteSnapshot,
PRIMARY_OUTLET,
ResolveFn,
RouterStateSnapshot,
TitleStrategy,
} from '@angular/router';
import { firstValueFrom, isObservable, Observable } from 'rxjs';
import { localeProvider } from '../locale';
/**
* A custom page title strategy can be used to append/prepend a page title with common wording.
* It is also helpful to recalculate the current page title on locale change.
*/
@Injectable({ providedIn: 'root' })
export class PageTitleStrategy extends TitleStrategy {
#title = inject(Title);
// https://angular.io/guide/router#setting-the-page-title
override updateTitle(state: RouterStateSnapshot) {
// Recalculate page title on locale change.
if (localeProvider.state === 'loading') {
const deepestRouteWithTitle = this.#getDeepestRouteWithTitle(state);
const routeTitle = deepestRouteWithTitle.routeConfig?.title as ResolveFn<string>;
if (typeof routeTitle === 'function') {
this.#unwrapAndSetTitle(routeTitle(deepestRouteWithTitle, state));
return;
}
}
const title = this.buildTitle(state);
if (title !== undefined) {
this.#setTitle(title);
}
}
#getDeepestRouteWithTitle(state: RouterStateSnapshot): ActivatedRouteSnapshot {
let routeWithTitle = state.root;
let nextRoute: ActivatedRouteSnapshot | undefined = routeWithTitle;
while (nextRoute !== undefined) {
nextRoute = nextRoute.children.find(child => child.outlet === PRIMARY_OUTLET);
if (nextRoute && this.getResolvedTitleForRoute(nextRoute)) {
routeWithTitle = nextRoute;
}
}
return routeWithTitle;
}
async #unwrapAndSetTitle(routeTitle: Observable<string> | Promise<string> | string) {
const title = await (isObservable(routeTitle) ? firstValueFrom(routeTitle) : routeTitle);
this.#setTitle(title);
}
#setTitle(title: string) {
this.#title.setTitle($localize`:@@fullPageTitle:${title}:pageTitle: | Application`);
}
}