Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Header and Footer content on Route Change in Angular

Tags:

angular

I am working on a simple Angular 2 app, and the routes I currently have are /login, /register, /home, and /profile.

On the main app component I have a <header> section, a <content> section, and a <footer> section. I currently have the <router-outlet></router-outlet> in the content section, but would also like to (sometimes) change some content in the header and footer components when there is different content in the content section.

I have researched child routing (and plan to use for some of the routes in the content section), but I am not sure if that's the best approach, or even possible. The child routing research I have done is from John Papa's Angular 2 course, and here is his example plunker: http://a2-first-look.azurewebsites.net/examples/router-child/plnkr.demo.html?bust=1463590738850

I have also explored subscribing to the router changes in the Header and Footer components, and render different html using *ngIf. This approach seems to create a whole new service SO 1, but this one seems a little more straightforward SO 2. I am thinking I can just doing something with the native Router directive?

Any help or a point in the right direction would be greatly appreciated! Thanks

like image 467
0xPingo Avatar asked May 18 '16 17:05

0xPingo


1 Answers

You could put this into your run block:

$rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
    SomeService.header.dynamicText = 'Hello, World'
    SomeService.footer.dynamicText = 'Contact Us'
})

Of course, you'll have to pass SomeService to your run function, as well.

More on this handy little service here

like image 137
Kraken Avatar answered Oct 12 '22 05:10

Kraken