[英]Binding header to text based on router url (Angular4)
使标题文本根据页面更改的最佳方法是什么? 我目前正在使用一个根据router.url更改颜色的单个标头(请参见此处的上一个问题),并且我想动态更改页面标头的文本。
我觉得逻辑也应该相似,如果我也想基于页面添加图像。
起初,我想遍历一系列标题,但最终只在所有页面上打印了所有标题。 然后我想创建一个函数来检查将检查链接并返回适当的标题,但是我不确定如何插入...
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.ts
export class AppComponent {
activatedRoute = '';
title: string;
pageTitles = [
{ 'title': 'About'},
{ 'title': 'Resources'},
{ 'title': 'News' },
{ 'title': 'Contact' }
];
activateRoute(activatedRoute: string) {
this.activatedRoute = activatedRoute;
}
getHeaderText() {
if (this.activatedRoute.includes('about')) {
this.title = 'About';
return this.title;
} else if (this.activatedRoute.includes('resources')) {
this.title = 'Resources';
return this.title;
} else if (this.activatedRoute.includes('newsroom')) {
this.title = 'News';
return this.title;
} else {
this.title = 'Contact';
return this.title;
}
}
constructor(private router: Router) {}
}
您不需要title
或pageTitles
。 创建用于获取活动页面标题的getter属性。
将您的组件html更改为:
<div class="set-margin page-title">
<h1>{{ headerTitle }}</h1>
</div>
...并在您的组件类中:
export class AppComponent {
activatedRoute = '';
activateRoute(activatedRoute: string) {
this.activatedRoute = activatedRoute;
}
get headerTitle {
if (this.activatedRoute.includes('about')) {
return 'About';
} else if (this.activatedRoute.includes('resources')) {
return 'Resources';
} else if (this.activatedRoute.includes('newsroom')) {
return 'News';
} else {
return 'Contact';
}
}
constructor(private router: Router) {}
}
您可以通过路由器将这些标题作为数据传递,看起来像这样
{ path: 'about', component: AboutComponent, data: {title: 'About Us'}},
{ path: 'resources', component: AboutComponent, data: {title: 'Amazing Resources'}},
{ path: 'newsroom', component: AboutComponent, data: {title: 'News'}},
首先,请确保在顶部添加这些导入
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Data } from '@angular/router';
那么您需要从路由器获取此数据。 您的AppComponent
可能看起来像这样
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上显示数据
{{ pageTitle }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.