Search code examples
angular

Angular 14 Access Route Config Title Property in Component


Is it possible to read the title out of the route.snapshot.data of the routeConfig in Angular 14? I can see it in the route.snapshot.data as a Symbol, but can't seem to access it:

{
  path: 'example',
  title: 'Title of Page',
  component: ExamplePage
}
this.route.snapshot.data[Symbol('RouteTitle')]) // undefined
console.log(this.route.snapshot.data) // { Symbol('RouteTitle'): 'Title of Page' }

I'm using the TitleStrategy to update the title to be:

${title} | ${companyName}`

But want to get the pre-strategy title in the component for use in the page so they match without using the Title service to getTitle and slicing the companyName off each time.


Solution

  • Get the title from the snapshot.routeConfig, it returns a Route that contains the snapshots title:

    {
      path: 'example',
      title: 'Title of Page',
      component: ExamplePage
    }
    
    @Component({/* Configuration */})
    export class ExamplePage implements OnInit {
    
      constructor(private readonly route: ActivatedRoute) { }
    
      ngOnInit() {
        console.log(this.route.snapshot.routeConfig?.title);
        // Output: Title of Page
      }
    }