-
-
Save ihor-lev/1858a06d8825f5c84fefbcd445bd1ffd to your computer and use it in GitHub Desktop.
Dynamically set page title based on active route in Angular 6+ .. (Corrected & Simplified Version)
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 { TitleService } from './shared/title/title.service'; | |
@Component({ | |
selector: 'ny-app', | |
templateUrl: './app.component.html', | |
styles: [], | |
}) | |
export class AppComponent implements OnInit { | |
constructor(private titleService: TitleService) { } | |
ngOnInit() { | |
this.titleService.boot(); | |
} | |
} |
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 ... | |
@NgModule({ | |
... | |
providers: [ TitleService ], | |
}) | |
export class AppModule { } |
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
const routes: Routes = [{ | |
path: '', | |
component: HomeComponent, | |
data: {title: "My Home Page"}, | |
}, { | |
path: 'detail/:id', | |
component: DetailComponent, | |
}]; | |
@NgModule({ | |
imports: [RouterModule.forChild(routes)], | |
exports: [RouterModule], | |
}) | |
export class ExampleRoutingModule { } |
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 { Injectable } from '@angular/core'; | |
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router'; | |
import { Title } from '@angular/platform-browser'; | |
import { filter, map, switchMap } from 'rxjs/operators'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class TitleService { | |
default_title = 'My App' | |
constructor( | |
private router: Router, | |
private activeRoute: ActivatedRoute, | |
private title: Title | |
) { } | |
boot() { | |
this.router.events.pipe( | |
filter(event => event instanceof NavigationEnd), | |
map(() => this.activeRoute), | |
map(route => route.firstChild), | |
switchMap(route => route.data), | |
map((data) => { | |
return data && data.title ? `${data.title} • ${this.default_title}` : this.default_title; | |
}) | |
).subscribe((current_title) => this.title.setTitle(current_title)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment