Created
April 22, 2017 02:31
-
-
Save x1unix/4f9b9687c1e9e73885e3a94772301b37 to your computer and use it in GitHub Desktop.
Angular 2 Route - Change page title based on route
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, OnInit } from '@angular/core'; | |
import { isNil } from 'lodash'; | |
import { ActivatedRoute, Router, NavigationEnd } from '@angular/router'; | |
import { Title } from '@angular/platform-browser'; | |
@Component({ | |
selector: 'l2-app', // <my-app></my-app> | |
templateUrl: './app.component.html', | |
styleUrls: ['./app.component.scss'], | |
}) | |
export class AppComponent implements OnInit { | |
constructor(private titleService: Title, private router: Router, private activatedRoute: ActivatedRoute) { | |
} | |
ngOnInit() { | |
// Subscribe for router navigation changes | |
this.router.events | |
.filter(event => event instanceof NavigationEnd) | |
.map(() => this.activatedRoute) | |
.map(route => { | |
while (route.firstChild) { route = route.firstChild; }; | |
return route; | |
}) | |
.filter(route => route.outlet === 'primary') | |
.mergeMap(route => route.data) | |
.subscribe((event) => { | |
// Apply page title for the new route | |
let title = isNil(event['title']) ? 'My App' : `My App | ${event['title']}`; | |
this.titleService.setTitle(title); | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { RouterModule, Routes } from '@angular/router'; | |
import { AboutComponent } from './about/about.component'; | |
import { AuthComponent } from './auth/auth.component'; | |
const routes: Routes = [ | |
{ | |
path: 'about', | |
component: AboutComponent, | |
data: { | |
title: 'About' | |
} | |
}, | |
{ | |
path: 'auth', | |
component: AuthComponent, | |
data: { | |
title: 'Authorization' | |
} | |
} | |
]; | |
export const routing = RouterModule.forRoot(routes); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment