Javascript 基于路由器url(Angular4)将标题绑定到文本
根据页面更改标题文本的最佳方式是什么?我目前正在使用一个基于router.url(见上一个问题)更改颜色的标题,我想动态更改页面标题文本 我觉得逻辑也应该是相似的,如果我也想添加基于页面的图像 起初我想迭代一系列的标题,但最终只是在所有页面上打印所有标题。然后我想创建一个函数,check将检查链接并返回适当的标题,但我不确定如何插入它 app.component.htmlJavascript 基于路由器url(Angular4)将标题绑定到文本,javascript,html,angular,Javascript,Html,Angular,根据页面更改标题文本的最佳方式是什么?我目前正在使用一个基于router.url(见上一个问题)更改颜色的标题,我想动态更改页面标题文本 我觉得逻辑也应该是相似的,如果我也想添加基于页面的图像 起初我想迭代一系列的标题,但最终只是在所有页面上打印所有标题。然后我想创建一个函数,check将检查链接并返回适当的标题,但我不确定如何插入它 app.component.html <!-- <div class="set-margin page-title"><h1 *ng
<!-- <div class="set-margin page-title"><h1 *ngFor="let pageTitle of pageTitles">{{ pageTitle.title }}</h1></div> -->
<div class="set-margin page-title">
<!-- <h1 *ngFor="let pageTitle of pageTitles">{{ pageTitle.title }}</h1> -->
<h1>{{ getHeaderText() }}</h1>
</div>
您不需要
标题
或页面标题
。创建用于获取活动页面标题的getter属性
将组件html更改为:
您可以通过路由器将这些标题作为数据传递,路由器看起来像这样
{ path: 'about', component: AboutComponent, data: {title: 'About Us'}},
{ path: 'resources', component: AboutComponent, data: {title: 'Amazing Resources'}},
{ path: 'newsroom', component: AboutComponent, data: {title: 'News'}},
export class AppComponent implements OnInit {
pageTitle = 'default page title';
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.data.subscribe(
(data: Data) => {
this.pageTitle = data['title'];
}
);
}
}
app.component.ts
首先,确保在顶部添加这些导入
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Data } from '@angular/router';
然后您需要从路由器获取这些数据。您的AppComponent
可能如下所示
{ path: 'about', component: AboutComponent, data: {title: 'About Us'}},
{ path: 'resources', component: AboutComponent, data: {title: 'Amazing Resources'}},
{ path: 'newsroom', component: AboutComponent, data: {title: 'News'}},
export class AppComponent implements OnInit {
pageTitle = 'default page title';
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.data.subscribe(
(data: Data) => {
this.pageTitle = data['title'];
}
);
}
}
然后在app.component.html上显示数据
<!-- <div class="set-margin page-title"><h1 *ngFor="let pageTitle of pageTitles">{{ pageTitle.title }}</h1></div> -->
<div class="set-margin page-title">
<!-- <h1 *ngFor="let pageTitle of pageTitles">{{ pageTitle.title }}</h1> -->
<h1>{{ getHeaderText() }}</h1>
</div>
app.component.html
{{ pageTitle }}