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

TypeScript unknown vs any types

The main difference between unknown and any is that unknown is much less permissive than any: we have to do some form of checking before performing most operations on values of type unknown, whereas we don't have to do any checks before performing operations on values of type any.

Angular Singapore

Follow @angularsg for the upcoming events :)


Follow @tuantrungvo on Twitter for more!