Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change page title in angular2 router

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 {} 
like image 710
B Hull Avatar asked Jan 05 '16 01:01

B Hull


People also ask

What is the correct code for changing the title of a page or document in angular?

We use SetTitle to set the title of the page and GetTitle to find out the current title of the page.

What is Title in angular?

A service that can be used to get and set the title of a current HTML document. class Title { getTitle(): string setTitle(newTitle: string) }

What is the use of ActivatedRoute?

ActivatedRoutelink. Provides access to information about a route associated with a component that is loaded in an outlet. Use to traverse the RouterState tree and extract information from nodes.

Why ActivatedRoute is used in angular?

ActivatedRoute Contains the information about a route associated with a component loaded in an outlet. It can also be used to pass data from one component to another component using route such as Id, flag, state etc.


1 Answers

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'
like image 65
drew moore Avatar answered Sep 27 '22 18:09

drew moore