Angular 14 route title and custom strategy

Angular 14 route title and custom strategy

Thanks to a new feature in the latest angular 14 version, we can set unique page titles with the new Route.title property in the Angular Router and we can also provide custom title strategies for advanced use cases.

For example:

import { Routes } from '@angular/router';

export const routes: Routes = [
  {
    path: 'home',
    title: 'Home Page',
    loadComponent: () =>
      import('./home/home.component').then(
        ({ HomeComponent }) => HomeComponent
      ),
  },
  {
    path: 'auth',
    title: 'Auth Page',
    loadComponent: () =>
      import('./auth/auth.component').then(
        ({ AuthComponent }) => AuthComponent
      ),
  },
];

The title property takes in the page title that gets changed when the route changes.

You can also configure more complex title logic by extending the TitleStrategy exported by @angular/router. For example, in the src/app/app-routing.module.ts file, add the following code:

import { Injectable } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { RouterStateSnapshot, Routes, TitleStrategy } from '@angular/router';


@Injectable()
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(`Angular 14 App - ${title}`);
    } else {
      this.title.setTitle(`Angular 14 App`);
    }
  }
}

export const routes: Routes = [
  {
    path: 'home',
    title: 'Home Page',
    loadComponent: () =>
      import('./home/home.component').then(
        ({ HomeComponent }) => HomeComponent
      ),
  },
  {
    path: 'auth',
    title: 'Auth',
    loadComponent: () =>
      import('./auth/auth.component').then(
        ({ AuthComponent }) => AuthComponent
      ),
  },
];

Next, open the src/main.ts file and update the providers array as follows:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { importProvidersFrom, enableProdMode } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { RouterModule, TitleStrategy } from '@angular/router';
import { routes, CustomTitleStrategy } from './app/app-routing.module';
import { AppComponent } from './app/app.component';

import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

bootstrapApplication(AppComponent, {
  providers: [
    importProvidersFrom(RouterModule.forRoot(routes), BrowserAnimationsModule),
    {
      provide: TitleStrategy,
      useClass: CustomTitleStrategy,
    },
  ],

The HomeComponent gets the title as "Angular 14 App" since it is the default title provided in the CustomTitleStrategy when you do not set the title property in the route configuration.


  • Date: