Skip to content

Instantly share code, notes, and snippets.

@ihor-lev
Forked from abarrak/app.component.ts
Created March 30, 2020 08:19
Show Gist options
  • Save ihor-lev/1858a06d8825f5c84fefbcd445bd1ffd to your computer and use it in GitHub Desktop.
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)
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();
}
}
import ...
@NgModule({
...
providers: [ TitleService ],
})
export class AppModule { }
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 { }
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