Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change header string in angular 2

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 enter image description here

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

like image 905
Smokey Dawson Avatar asked Nov 13 '17 04:11

Smokey Dawson


Video Answer


1 Answers

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

like image 154
Aamir Khan Avatar answered Sep 28 '22 03:09

Aamir Khan