With Angular 14, Now we can generate dynamic tab titles with ease.
1. Title property in Routes
Use Case:
- Users page with users as tab name.(Users)
- Orders page with orders as tab name(Orders)
Then simply use title property in Routes as below
Code
export const APP_ROUTES: Routes = [
{path: '/users', component: UsersComponent, title: 'Users'},
{path: '/orders', component: OrdersComponent, title: 'Orders'}
];
2. Title with Resolve
Use Case:
- Users page with current user name in tab name.(User- Bharath)
- Orders page with order id in tab name.(Order Id:1)
Then we should create a service which implement Resolve
class from Router module as shown below.
Code:
@Injectable({
providedIn: "root"
})
export class CustomTitleResolver implements Resolve<string> {
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<string> | Promise<string> | string {
// Have fun with naming
return "<<project-name>> -" + route.paramMap.get("id") || "";
}
}
Update Routes with title property
export const APP_ROUTES: Routes = [
{path: '/users/:id', component: UsersComponent, title: CustomTitleResolver },
{path: '/orders/:id', component: OrdersComponent, title: CustomTitleResolver }
];
3. Title Strategy
Use Case:
If you want a more generalized pattern, that will be applied **all over the application.
- Prefixing a text to tab title.(Project X Users)
- Suffixing a text to tab title.(Users Project X )
Then create a service that extends TitleStrategy
and add it as Provider in AppModule.
Code
@Injectable({
providedIn: "root"
})
export class CustomTitleStrategy extends TitleStrategy {
constructor(private readonly title: Title) {
super();
}
override updateTitle(routerState: RouterStateSnapshot): void {
const title = this.buildTitle(routerState);
if (title !== undefined) {
this.title.setTitle(`myImpact (${title})`);
} else {
this.title.setTitle('myImpact');
}
}
}
Naming Strategy should be added as provider in app module, so that angular is aware that you have provided an alternative Naming strategy.
@NgModule({
declarations: [
],
imports: [
],
providers: [{
provide: TitleStrategy,
useClass: IAMTitleStrategy
}],
bootstrap: [AppComponent]
})
export class AppModule {
}
Note
Depending on your use case, you can use either of these ways and also mix up both Resolve and naming Strategy like me
Happy coding π¨βπ» !!
Top comments (0)