Page Title Strategy

January 26, 2024 · 4 min readLucian Ciobanu
Tags:AngularTypeScript

The project I am mostly involved in at the moment is really challenging as it isthe first projects I am delivering to be public facing at a very big scale so my limits are being pushed by implementing digital marketing specific tasks such as having a dynamic title of the page composed of a base, id of the item viewed (when viewed) and a suffix containing the name of the app.

I found some information in Angular's documentation and some quick scribbles in stack blitz or stack overflow but, as always, implementing something specific goes beyond just googling and copy-pasting the first result.

The first challenge of the task was to capture the parameters being shown in the URL and make them available via a service:

app.component.ts

...
constructor(private router: Router) {}
...
ngOnInit(): void {
  this.router.events.forEach((event) => {
    if (event instanceof NavigationEnd) {
      const mergedParams = this.mergeRouteParams(this.router);
      this.appService.setRoutingParams(mergedParams);
    }
  });
}

private mergeRouteParams(router: Router): { [key: string]: string } {
  let params = {};
  let route = router.routerState.snapshot.root;
  do {
    params = { ...params, ...route.params };
    route = route.firstChild!;
  } while (route);
  return params;

After this, I created a new strategy for page title:

page-title.strategy.ts

import { Injectable } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { RouterStateSnapshot, TitleStrategy } from '@angular/router';
import { AppService } from '../services/app.service';

@Injectable()
export class PageTitleStrategy extens TitleStrategy {
  constructor(
    private title: Title,
    private appService: AppService
  ) {
    super();
    this.appService.routingParamsSubject$
      .subscribe((params) => {
      const paramKeys = Object.keys(params);
      const lastParam = paramKeys.pop();
      this.id = params[lastParam!];
    });
  }
  
  id: string | undefined;
  
  override updateTitle(routerState: RouterStateSnapshot) {
    const baseTitle = '| Lucian App Pro';
    const title = this.buildTitle(routerState);
    if (tittle && this.id) {
      this.title.setTitle(`${title} ${this.id} ${baseTitle}`);
    } else if {
      this.title.setTitle(`${title} ${baseTitle}`);
    } else {
      this.title.setTitle(`Lucian App Pro`);
    }
  }
}

This part has given me the biggest headache as subscribing to the subject was triggering the buildTitle after navigation end and I was still getting some residual values which were completely messing up my naming.

Another very important step is to make the strategy available in the router.

app-routing.module.ts

const routes: Routes = [
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModules],
  providers: [
    provideRouter(routes, withComponentInputBinding()), //I love this so much!!
    {
      provide: TitleStrategy,
      useClass: PageTitleStrategy,
    }
  ],
})
                                    

Also, each route should have a title to be found by the buildTitle property:

main.routes.ts

{
  path: 'admin',
  title: 'Admin',
  loadChildren: () => ..
}

So in the end, what the code does is to take the title like 'Admin', add the id of the viewed admin if needed we are viewing someone and append | Lucian App Pro at the end.

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery