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
Our code will basically do:
const routes: Routes = [
{
path: '',
component: HomeComponent,
data: {
title: 'Home',
},
},
{
path: 'dashboard',
component: DashboardComponent,
data: {
title: 'Dashboard',
},
},
]
app.component.ts
, setup the listener and extract the titleexport 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
}
Open angular-auto-set-page-title.stackblitz.io to view it on your browser.