In my app Im trying to dynamically change the title in my header component depending on the page that Im on, so In my header component I want to use a
<h1>{{title}}</h1>
and I want it to change depending on the page that I am on. Now the header is fixed so it's on every page
below is an image of what im trying to change
Basically if im on the home page I want it to say home and then if Im on an about page I want it to change to about..
Not sure how I can go about this and everything ive researched has been to change the title in the <head></head>
tags
You can create a service dedicated for updating the title in your header component. Simply inject the service in your header component and subscribe to a dedicated BehaviorSubject. Then you can inject this service in any component you have and use the setTitle method from that component which will update the title in the header component. Check out the following code
//headerTitle.service.ts
@Injectable()
export class headerTitleService {
title = new BehaviorSubject('Initial Title');
setTitle(title: string) {
this.title.next(title);
}
}
//header.component.ts
title = '';
constructor(private headerTitleService: HeaderTitleService) {}
ngOnInit() {
this.headerTitleService.title.subscribe(updatedTitle => {
this.title = updatedTitle;
});
}
//header.component.html
<h1>{{title}}</h1>
//about.component.ts
constructor(private headerTitleService: HeaderTitleService) {}
ngOnInit() {
this.headerTitleService.setTitle('About');
}
Working demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With