DEV Community

Junaid Ramzan
Junaid Ramzan

Posted on

How to set page title in angular 14

In the new version of angular 14 a new cool feature has been added that allows to set the page title easily based on the current route that is rendered.

The Route interface has been expanded with a new property called title.

This property can be either a static string or a custom resolver to set a dynamic title.

Example:

export const routes: Routes = [
  {
    path: 'hello',
    title: 'Hello!',
    ...
  }
]
Enter fullscreen mode Exit fullscreen mode

With Resolver:

@Injectable({ providedIn: 'root' })
class HelloTitleResolver implements Resolve<string> {
  constructor(private randomEmoji: RandomEmojiService) { }

  resolve(route: ActivatedRouteSnapshot) {
    return this.randomEmoji.emoji().pipe(
      map(e => `Hello ${e}!`)
    );
  }
}
Enter fullscreen mode Exit fullscreen mode
export const routes: Routes = [
  {
    path: 'hello',
    title: HelloTitleResolver,
    ...
  }
]
Enter fullscreen mode Exit fullscreen mode

Angular also provides a PageTitleStrategy that allows to set a global strategy to handle the title for all routes.

Top comments (0)