使用Angular动态修改页面标题
首先
在开发SPA(单页应用)的Web应用程序时,您是否曾经想过要为每个页面更改标题?
虽然Angular具备更改标题的标准功能,但通过添加一些实现,您可以为每个页面设置标题。
以下我将介绍两种更改标题的方法。
请示范
请看一个包含标题更改的应用程序演示。
您可以在以下时机确认可以更改标题。
-
- 当屏幕切换到「Go To title1」或「Go To title2」时,
- 当按下「ChangeTitle」或「RestoreTitle」按钮时。

实施
使用任何值来更改标题
通过执行 Angular 提供的 @angular/platform-browser 模块中的 setTitle() 方法,可以更改标题。
在示例中,我们将与 input 绑定的值设置为 setTitle() 的参数,并在按下按钮时更新标题。
HTML
Typescript
import { Component } from “@angular/core”;
import { Title } from “@angular/platform-browser”;
@Component({
selector: “app-home”,
templateUrl: “./home.component.html”,
styleUrls: [“./home.component.scss”],
})
export class HomeComponent {
public title = “AngularTitleChange”;
constructor(private titleService: Title) {}
public changeTitle() {
this.titleService.setTitle(this.title);
}
public restoreTitle() {
this.title = “AngularTitleChange”;
this.changeTitle();
}
}
当进行页面跳转时,自动更改标题。
在app.component.ts中订阅NavigationEnd事件,并在页面转换时调用setTitle()函数来更改标题。每个页面的标题通过在app-routing.module.ts中添加data: { title: ‘Title1’ }的附加信息来反映。
app.component.ts
import { Component, OnInit } from “@angular/core”;
import { Title } from “@angular/platform-browser”;
import { ActivatedRoute, NavigationEnd, Router } from “@angular/router”;
import { filter, map } from “rxjs/operators”;
@Component({
selector: “app-root”,
templateUrl: “./app.component.html”,
styleUrls: [“./app.component.scss”],
})
export class AppComponent implements OnInit {
constructor(
private titleService: Title,
private router: Router,
private activatedRoute: ActivatedRoute
) {}
ngOnInit() {
const appTitle = this.titleService.getTitle();
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => {
const child = this.activatedRoute.firstChild;
if (child.snapshot.data.title) {
return child.snapshot.data.title;
}
return appTitle;
})
)
.subscribe((ttl: string) => {
this.titleService.setTitle(ttl);
});
}
}
app-routing.module.ts
const routes: Routes = [
{
path: “”,
component: HomeComponent,
},
{
path: “title1”,
component: Title1Component,
data: { title: “Title1” },
},
{
path: “title2”,
component: Title2Component,
data: { title: “Title2” },
},
];
请提供以下中文的同义词(只需要一种选择):
参考