how to change page title in angular2 router

The Title service @EricMartinez points out has a setTitle() method – that’s all you need to set the title.

In terms of doing it automatically on route changes, as of now there’s no built-in way of doing this other than subscribing to Router and calling setTitle() in your callback:

import {RouteConfig} from 'angular2/router';
import {Title} from 'angular2/platform/browser';

@RouteConfig([
  {path: '/home', component: HomeCmp, name: 'HomeCmp' }
])
class MyApp {
    constructor(router:Router, title:Title) {
       router.events.subscribe((event)=>{ //fires on every URL change
          title.setTitle(getTitleFor(router.url));
       });
    }
 }

That said, I emphasize as of now because the router is still under heavy development, and I expect (or at least hope) that we’ll be able to do this via RouteConfig in the final release.

EDIT:

As of the release of Angular 2 (2.0.0), a few things have changed:

  • The docs for the Title service are now here: https://angular.io/docs/ts/latest/api/platform-browser/index/Title-class.html
  • The service is imported from '@angular/platform-browser'

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)