Wanna see something cool? Check out Angular Spotify 🎧
All Articles

Angular - Set page title automatically!

Hey guys, long time no Angular post.

I have been busy with Angular Spotify and Angular Singapore.

Today, I’ll share a block of code with you that my friend @nartc mentioned recently.

That’s how the output looks like

Angular - auto set page title

What we will do

Our code will basically do:

  • Listen to Router events
  • Filter the ResolveEnd events
  • Find the deepest activated route (usually is the current activated component)
  • Get the data.title that we set up on the router configuration
  • Set the HTML document title with the found title.

Source code

  1. First, we need to configure the router with an additional title
const routes: Routes = [
  {
    path: '',
    component: HomeComponent,
    data: {
      title: 'Home',
    },
  },
  {
    path: 'dashboard',
    component: DashboardComponent,
    data: {
      title: 'Dashboard',
    },
  },
]
  1. On the app.component.ts, setup the listener and extract the title
export class AppComponent implements OnInit {
  name = 'Angular ' + VERSION.major
  constructor(private readonly title: Title, private readonly router: Router) {}

  ngOnInit() {
    this.setupTitleListener()
  }

  private setupTitleListener() {
    this.router.events
      .pipe(filter(e => e instanceof ResolveEnd))
      .subscribe((e: ResolveEnd) => {
        const { data } = getDeepestChildSnapshot(e.state.root)
        if (data?.title) {
          console.log(data.title)
          this.title.setTitle(data.title)
        }
      })
  }
}

function getDeepestChildSnapshot(snapshot: ActivatedRouteSnapshot) {
  let deepestChild = snapshot.firstChild
  while (deepestChild?.firstChild) {
    deepestChild = deepestChild.firstChild
  }
  return deepestChild || snapshot
}
  1. Voila, that’s all

Demo

Open angular-auto-set-page-title.stackblitz.io to view it on your browser.

Published 1 May 2021

Recent Posts

A simple Spotify client built with Angular 11, Nx workspace, ngrx, TailwindCSS and ng-zorro

An example of real-world monorepo codebase using Nx Workspace

Nx Workspace structure for an application with NestJS and Angular

This structure has been serving us really really well by enforcing consistency, promoting SCAM, prevent circular dependencies, and minimize mental overhead of "where to put what"


Follow @tuantrungvo on Twitter for more!