如何在angular2路由器中更改页面标题 [英] 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 {}
推荐答案
Title
服务@EricMartinez 指出 有一个 setTitle()
方法 - 这就是你设置标题所需的全部内容.
The Title
service @EricMartinez points out has a setTitle()
method - that's all you need to set the title.
就在路由更改时自动执行此操作而言,截至目前,除了订阅 Router
并在您的回调中调用 setTitle()
:
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));
});
}
}
也就是说,我强调目前,因为路由器仍在大量开发中,我希望(或至少希望)我们能够通过 RouteConfig 做到这一点
在最终版本中.
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.
随着 Angular 2 (2.0.0) 的发布,一些事情发生了变化:
As of the release of Angular 2 (2.0.0), a few things have changed:
Title
服务的文档现在在这里:https://angular.io/docs/ts/latest/api/platform-browser/index/Title-class.html- 服务是从
'@angular/platform-browser'
导入的
- 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'
这篇关于如何在angular2路由器中更改页面标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!