Scenario and Issue
I have set up various routes in my app-routing.module
like this:
// imports
const routes: Routes = [
{ path: 'home', title: 'Home Route', component: HomeComponent },
{ path: 'other', title: 'Other Route', component: OtherComponent},
{ path: 'another', title: 'Yet Another Route', component: YetAnotherComponent },
{ path: '', redirectTo: 'home', pathMatch: 'full' },
];
@NgModule({
declarations: [],
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Additionally, I have created a navigation-title.component
that is meant to display the current route as "My App | Home Route"
or "My App | Other Route"
, and so on.
However, I am facing a challenge in binding to the route title effectively.
Attempts Made
Utilizing ActivatedRoute
in the navigation-title
component
Initially, I attempted to inject
private activatedRoute: ActivatedRoute
and bind to this.activatedRoute.title
(an Observable<string | undefined>
) with an async
pipe. However, it seems that this activated route does not update dynamically during navigation.
Listening to router navigation events
Next, I tried subscribing to router events, specifically to NavigationEnd
, to update the title. Unfortunately, retrieving the title from the activated route after navigation always fetched the previous route's title.
Binding to the router outlet
Lastly, I bound to the router-outlet
's (activate)
event with an event handler inside my navigation-title.component
. This method led to tight coupling between the title component and the router outlet.
Is there a more efficient (i.e. completely decoupled) way to simply fetch the route title using an injected Router
or ActivatedRoute
?
Note
I emphatically do not wish to utilize the TitleService
because it seems redundant to allow a component to set the page title when it can already be defined within the corresponding route.