Set angular 2 dynamic page title

Create a title service class name like title.service.ts and put below code.

import { Injectable } from ‘@angular/core’;

import ‘rxjs/add/operator/filter’;
import ‘rxjs/add/operator/map’;
import ‘rxjs/add/operator/mergeMap’;

import { Router, NavigationEnd, ActivatedRoute } from ‘@angular/router’;
import { Title } from ‘@angular/platform-browser’;

const APP_TITLE = ‘My App’;
const SEPARATOR = ‘ | ‘;

@Injectable()
export class TitleService {
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
private titleService: Title,
) {}

init() {
this.router.events
.filter((event) => event instanceof NavigationEnd)
.map(() => {
let route = this.activatedRoute;
while (route.firstChild) route = route.firstChild;
return route;
})
.filter((route) => route.outlet === ‘primary’)
.mergeMap((route) => route.data)
.map((data) => {
if ( data.title ) {
// If a route has a title set (e.g. data: {title: “Foo”}) then we use it
return data.title;
} else {
// If not, we do a little magic on the url to create an approximation
return this.router.url.split(‘/’).reduce((acc, frag) => {
if ( acc && frag ) { acc += SEPARATOR; }
return acc + TitleService.ucFirst(frag);
});
}
})
.subscribe((pathString) => this.titleService.setTitle(`${APP_TITLE} ${SEPARATOR} ${pathString}`));
}

static ucFirst(string) {
if ( !string ) { return string; }
return string.charAt(0).toUpperCase() + string.slice(1);
}
}

 

Next, you have add this service to your app.module.ts file
import {TitleService} from “./title.service”;

and add this service to providers array
@NgModule({
declarations: [
AppComponent,
BlogComponent,
FontcolorDirective
],
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } // debugging purposes only
)
],
providers: [TitleService],
bootstrap: [AppComponent]
})

Next, you have to add below code on app.component.ts file for importing the service and init the service on ngOnInit method.
import {TitleService} from “./title.service”;

export class AppComponent implements OnInit {

constructor(private titleService: TitleService) {}

ngOnInit(): void {
this.titleService.init();
}
}

If you do not have any route then you have to add route to test this or executing this functionality.

Here, i have declare a blog route and i have set the title as Blogs like below.

const appRoutes: Routes = [
{ path: ‘blog’, component: BlogComponent , data: { title: ‘Blogs’ }},

];

Finally, if you click this blog link you see the title MyApp | Blogs like below screenshot.

Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *