我正在尝试从路由器更改页面标题,可以这样做吗?
import {RouteConfig} from 'angular2/router';
@RouteConfig([
{path: '/home', component: HomeCmp, name: 'HomeCmp' }
])
class MyApp {}
答案 0 :(得分:54)
Title
service @EricMartinez points out有setTitle()
方法 - 这就是设置标题所需的全部内容。
就在路线更改时自动执行此操作而言,截至目前除了订阅Router
并调用{{1>之外,没有其他内置方法可以执行此操作在你的回调中:
setTitle()
那就是说,我强调截至目前因为路由器仍处于大量开发阶段,我希望(或者至少希望)我们能够通过{{ 1}}在最终版本中。
编辑:
自Angular 2(2.0.0)发布以来,发生了一些变化:
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));
});
}
}
服务的文档现在位于https://angular.io/docs/ts/latest/api/platform-browser/index/Title-class.html RouteConfig
答案 1 :(得分:15)
这里的方法很好,特别是对于嵌套路线:
我使用递归辅助方法在路由更改后获取最深的可用标题:
@Component({
selector: 'app',
template: `
<h1>{{title | async}}</h1>
<router-outlet></router-outlet>
`
})
export class AppComponent {
constructor(private router: Router) {
this.title = this.router.events
.filter((event) => event instanceof NavigationEnd)
.map(() => this.getDeepestTitle(this.router.routerState.snapshot.root));
}
title: Observable<string>;
private getDeepestTitle(routeSnapshot: ActivatedRouteSnapshot) {
var title = routeSnapshot.data ? routeSnapshot.data['title'] : '';
if (routeSnapshot.firstChild) {
title = this.getDeepestTitle(routeSnapshot.firstChild) || title;
}
return title;
}
}
这是假设您已在路线的数据属性中分配了页面标题,如下所示:
{
path: 'example',
component: ExampleComponent,
data: {
title: 'Some Page'
}
}
答案 2 :(得分:13)
对于Angular 4 +:
如果要使用路径自定义数据为每个路径路径定义页面标题,则以下方法适用于嵌套路径和角度版本4 +:
您可以在路线定义中传递页面标题:
{path: 'home', component: DashboardComponent, data: {title: 'Home Pag'}},
{path: 'about', component: AboutUsComponent, data: {title: 'About Us Page'}},
{path: 'contact', component: ContactUsComponent, data: {title: 'Contact Us Pag'}},
现在,在您的上层组件中最重要的(即AppComponent
),您可以在每次路线更改时全局捕获路线自定义数据并更新页面标题:
import {Title} from "@angular/platform-browser";
export class AppComponent implements OnInit {
constructor(
private activatedRoute: ActivatedRoute,
private router: Router,
private titleService: Title
) { }
ngOnInit() {
this.router
.events
.filter(event => event instanceof NavigationEnd)
.map(() => {
let child = this.activatedRoute.firstChild;
while (child) {
if (child.firstChild) {
child = child.firstChild;
} else if (child.snapshot.data && child.snapshot.data['title']) {
return child.snapshot.data['title'];
} else {
return null;
}
}
return null;
}).subscribe( (title: any) => {
this.titleService.setTitle(title);
});
}
}
上述代码针对角度4 +进行测试。
答案 3 :(得分:9)
这样做非常容易,您可以按照以下步骤查看即时效果:
我们在bootstrap中提供Title服务:
import { NgModule } from '@angular/core';
import { BrowserModule, Title } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
imports: [
BrowserModule
],
declarations: [
AppComponent
],
providers: [
Title
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
然后在您想要的组件中导入此服务:
import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
@Component({
selector: 'my-app',
template:
`<p>
Select a title to set on the current HTML document:
</p>
<ul>
<li><a (click)="setTitle( 'Good morning!' )">Good morning</a>.</li>
<li><a (click)="setTitle( 'Good afternoon!' )">Good afternoon</a>.</li>
<li><a (click)="setTitle( 'Good evening!' )">Good evening</a>.</li>
</ul>
`
})
export class AppComponent {
public constructor(private titleService: Title ) { }
public setTitle( newTitle: string) {
this.titleService.setTitle( newTitle );
}
}
现在点击这些链接以查看标题更改。
你也可以使用ng2-meta来改变页面标题和描述,你可以参考这个链接:
答案 4 :(得分:5)
Angular 2提供Title Service看Shailesh答案只是该代码的副本。
我的app.module.ts
import { BrowserModule, Title } from '@angular/platform-browser';
........
providers: [..., Title],
bootstrap: [AppComponent]
现在转到我们的app.component.ts
import { Title } from '@angular/platform-browser';
......
export class AppComponent {
public constructor(private titleService: Title ) { }
public setTitle( newTitle: string) {
this.titleService.setTitle( newTitle );
}
}
将标题标记放在组件html上,它将为您读取和设置。
如果您想知道如何动态设置它并further detail see this article
答案 5 :(得分:2)
这就是我的目的:
constructor(private router: Router, private title: Title) { }
ngOnInit() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.title.setTitle(this.recursivelyGenerateTitle(this.router.routerState.snapshot.root).join(' - '));
}
});
}
recursivelyGenerateTitle(snapshot: ActivatedRouteSnapshot) {
var titleParts = <string[]>[];
if (snapshot) {
if (snapshot.firstChild) {
titleParts = titleParts.concat(this.recursivelyGenerateTitle(snapshot.firstChild));
}
if (snapshot.data['title']) {
titleParts.push(snapshot.data['title']);
}
}
return titleParts;
}
答案 6 :(得分:1)
import {Title} from "@angular/platform-browser";
@Component({
selector: 'app',
templateUrl: './app.component.html',
providers : [Title]
})
export class AppComponent implements {
constructor( private title: Title) {
this.title.setTitle('page title changed');
}
}
答案 7 :(得分:1)
在下面的示例中:
- 我们添加了数据对象:{title:&#39; NAME&#39;任何路由对象。
- 我们设置一个基本名称(&#34; CTM&#34;)用于上传时间(点击F5进行Refreash ..):home{
.segment-button {
color: red; //as suggested by @Mr_Perfect
}
}
。
- 我们添加了#34; TitleService&#34;类。
- 我们通过从app.component.ts过滤它们来处理Routher事件。
index.html:
<title>CTM</title>
...
<强> app.module.ts:强>
<!DOCTYPE html>
<html>
<head>
<base href="/">
<title>CTM</title>
</head>
<强> title.service.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();
应用-routing.module.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 = <string[]>[];
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.component.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];
答案 8 :(得分:1)
Angular 6 + 我使用新的Pipe()修改了旧代码,并且工作正常。
import { Title } from '@angular/platform-browser';
import { filter, map, mergeMap } from 'rxjs/operators';
...
constructor(
private router: Router,
public activatedRoute: ActivatedRoute,
public titleService: Title,
) {
this.setTitle();
}
...
setTitle() {
this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => this.activatedRoute),
map((route: any) => {
while (route.firstChild) route = route.firstChild;
return route;
}),
filter((route) => route.outlet === 'primary'),
mergeMap((route: any) => route.data)).subscribe((event) => {
this.titleService.setTitle(event['title']);
console.log('Page Title', event['title']);
})
}
答案 9 :(得分:1)
使用管道和贴图方法而不是使用过滤器,可以在Angular 6和6+中正常工作
第1步:路由设置
{path: 'dashboard', component: DashboardComponent, data: {title: 'My Dashboard'}},
{path: 'aboutUs', component: AboutUsComponent, data: {title: 'About Us'}},
{path: 'contactUs', component: ContactUsComponent, data: {title: 'Contact Us Page'}},
第二步:在您的app.module.ts导入模块中
import { BrowserModule, Title } from '@angular/platform-browser';
然后在提供者中添加提供者:[title]
第3步 在您的主要组件导入中
import { Title } from "@angular/platform-browser";
import { RouterModule, ActivatedRoute, Router, NavigationEnd } from "@angular/router";
import { filter, map } from 'rxjs/operators';
constructor(private titleService: Title, private router: Router, private activatedRoute: ActivatedRoute) {
}
ngOnInit() {
this.router.events.pipe(map(() => {
let child = this.activatedRoute.firstChild;
while (child) {
if (child.firstChild) {
child = child.firstChild;
} else if (child.snapshot.data && child.snapshot.data['title']) {
return child.snapshot.data['title'];
} else {
return null;
}
}
return null;
})).subscribe(title => {
this.titleService.setTitle(title);
});
}
答案 10 :(得分:0)
如果您正在寻找一种动态设置页面标题和元标记的方法,我还可以推荐我刚刚发布的@ngx-meta/core插件插件。
答案 11 :(得分:0)
Angular 6 +
如果路由配置如下:-
Routes = [
{ path: 'dashboard',
component: DashboardComponent,
data: {title: 'Dashboard'}
}]
**然后可以在组件构造器标题中设置如下:-**
constructor( private _titleService: Title, public activatedRoute: ActivatedRoute) {
activatedRoute.data.pipe(map(data => data.title)).subscribe(x => this._titleService.setTitle(x));
}
答案 12 :(得分:0)
设置标题的简单通用方法:
import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor(
private activatedRoute: ActivatedRoute,
private router: Router,
private titleService: Title
) {}
ngOnInit() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
const { title } = this.activatedRoute.firstChild.snapshot.data;
this.titleService.setTitle(title);
}
});
}
}
需要在每个路由上设置title
,例如:
{ path: '', component: WelcomeComponent, data: {title: 'Welcome to my app'} }