I am trying to change the page title from the router, can this be done?
import {RouteConfig} from \'angular2/router\';
@RouteConfig([
{path: \'/home\', com
In the below example:
-We added object of data: { title: 'NAME' } to any routing object.
-We set a basic name ("CTM") for uploading time (when clicking F5 for Refreash..): .
-We added "TitleService" class.
-we handle Routher events by filtering them from app.component.ts.
index.html:
CTM
...
app.module.ts:
import { NgModule, enableProdMode } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TitleService } from './shared/title.service';
...
@NgModule({
imports: [
BrowserModule,
..
],
declarations: [
AppComponent,
...
],
providers: [
TitleService,
...
],
bootstrap: [AppComponent],
})
export class AppModule { }
enableProdMode();
title.service.ts:
import { Injectable } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ActivatedRouteSnapshot } from '@angular/router';
@Injectable()
export class TitleService extends Title {
constructor() {
super();
}
private recursivelyGenerateTitle(snapshot: ActivatedRouteSnapshot) {
var titleParts = [];
if (snapshot) {
if (snapshot.firstChild) {
titleParts = this.recursivelyGenerateTitle(snapshot.firstChild);
}
if (snapshot.data['title']) {
titleParts.push(snapshot.data['title']);
}
}
return titleParts;
}
public CTMGenerateTitle(snapshot: ActivatedRouteSnapshot) {
this.setTitle("CTM | " + this.recursivelyGenerateTitle(snapshot).join(' - '));
}
}
app-routing.module.ts:
import { Injectable } from '@angular/core';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MainComponent } from './components/main.component';
import { Router, CanActivate } from '@angular/router';
import { AuthGuard } from './shared/auth/auth-guard.service';
import { AuthService } from './shared/auth/auth.service';
export const routes: Routes = [
{ path: 'dashboard', component: MainComponent, canActivate: [AuthGuard], data: { title: 'Main' } },
];
@NgModule({
imports: [
RouterModule.forRoot(routes, { useHash: true }) // .../#/crisis-center/
],
exports: [RouterModule],
providers: [
..
]
})
export class AppRoutingModule { }
export const componentsOfAppRoutingModule = [MainComponent];
app.component.ts:
import { Component } from '@angular/core';
import { Router, NavigationEnd, ActivatedRouteSnapshot } from '@angular/router';
import { TitleService } from './shared/title.service';
@Component({
selector: 'ctm-app',
template: `
`
})
export class AppComponent {
constructor(private router: Router, private titleService: TitleService) {
this.router.events.filter((event) => event instanceof NavigationEnd).subscribe((event) => {
console.log("AppComponent.constructor: Setting HTML document's Title");
this.titleService.CTMGenerateTitle(this.router.routerState.snapshot.root);
});
}
}