Are you setting your title in the router, or in a component?
UPDATE: I’ve just re-read the original question, and you do mention the page title is in your component. I tried like heck to get app.component.ts to retrieve the dynamic page title which was set in the currently displayed component, but was unable to do so. I experienced the same behavior that you described in your question: it kept returning the title from the previously clicked page, even when I tried to grab the title from the DOM document object.
I had to move my page title from the page component to app.routing-module.js to get app.component.ts to retrieve the correct current title.
Like you, I needed my title to be dynamic. I have Angular 14 and was able to set a dynamic title in the router via a resolver, and use the new TitleStrategy.getResolvedTitleForRoute() to return the title.
If you are still using an older version of Angular, then the below method will work for you … you just have to figure out how to set a title dynamically in the routing module :-)
ACCESSING CURRENT PAGE TITLE FROM APP.COMPONENT.TS VIA THE ROUTER
Let's say your app-routing module looks something like this...
app-routing.module.ts
const routes: Routes = [
{
path: 'posts/:postId',
component PostDetailPageComponent,
data: { title: 'My App - Post Page' }
},
{
path: 'users/:userId',
component: UserDetailComponent,
data: { title: 'My App - User Page' }
]
You should be able to access the titles in app.component.ts this way:
app.component.ts
import { Component } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router, RouterState } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'My Generic Title';
constructor(private router: Router) { this.handleRouteEvents() }
handleRouteEvents() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
const p_title = this.getTitle(this.router.routerState, this.router.routerState.root).join('-');
const p_path = event.urlAfterRedirects;
const p_location = this._document.location.href;
console.log('p_title: |', p_title, '|');
console.log('p_path: ', p_path);
console.log('p_location: ', p_location);
}
});
}
getTitle(state: RouterState, parent: ActivatedRoute): string[] {
const data = [];
if (parent && parent.snapshot.data && parent.snapshot.data['title']) {
data.push(parent.snapshot.data['title']);
}
if (state && parent && parent.firstChild) {
data.push(...this.getTitle(state, parent.firstChild));
}
return data;
}
}
I hope this helps you out!