how to change page title in angular2 router

B Hull picture B Hull · Jan 5, 2016 · Viewed 43.6k times · Source

I am trying to change the page title from the router, can this be done?

import {RouteConfig} from 'angular2/router';
@RouteConfig([
  {path: '/home', component: HomeCmp, name: 'HomeCmp' }
])
class MyApp {}

Answer

drew moore picture drew moore · Jan 5, 2016

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: