typescript 以角度 2 动态更改标题字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47257167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically change header string in angular 2
提问by Smokey Dawson
In my app Im trying to dynamically change the title in my header component depending on the page that Im on, so In my header component I want to use a
在我的应用程序中,我试图根据我所在的页面动态更改标题组件中的标题,因此在我的标题组件中,我想使用
<h1>{{title}}</h1>
and I want it to change depending on the page that I am on. Now the header is fixed so it's on every page
我希望它根据我所在的页面而改变。现在标题是固定的,所以它在每一页上
below is an image of what im trying to change
Basically if im on the home page I want it to say home and then if Im on an about page I want it to change to about..
基本上,如果我在主页上,我希望它说家,然后如果我在关于页面上,我希望它更改为 about..
Not sure how I can go about this and everything ive researched has been to change the title in the <head></head>
tags
不知道我该怎么做,我研究的所有内容都是更改<head></head>
标签中的标题
回答by Aamir Khan
You can create a service dedicated for updating the title in your header component. Simply inject the service in your header component and subscribe to a dedicated BehaviorSubject. Then you can inject this service in any component you have and use the setTitle method from that component which will update the title in the header component. Check out the following code
您可以创建一个专门用于更新标题组件中的标题的服务。只需在您的标头组件中注入服务并订阅专用的BehaviorSubject。然后,您可以在您拥有的任何组件中注入此服务,并使用该组件中的 setTitle 方法,该方法将更新标题组件中的标题。看看下面的代码
//headerTitle.service.ts
@Injectable()
export class headerTitleService {
title = new BehaviorSubject('Initial Title');
setTitle(title: string) {
this.title.next(title);
}
}
//header.component.ts
title = '';
constructor(private headerTitleService: HeaderTitleService) {}
ngOnInit() {
this.headerTitleService.title.subscribe(updatedTitle => {
this.title = updatedTitle;
});
}
//header.component.html
<h1>{{title}}</h1>
//about.component.ts
constructor(private headerTitleService: HeaderTitleService) {}
ngOnInit() {
this.headerTitleService.setTitle('About');
}
回答by lokesh nagpal
Use the title service in @angular/platform-browser and add router component with data property.
使用@angular/platform-browser 中的标题服务并添加具有数据属性的路由器组件。
const appRoutes: Routes = [
{ path: 'home',component:HomeComponent , data:{title:'Home'}}
];
Call this function in the root component
在根组件中调用此函数
ngOnInit() {
this.router.events
.filter((event) => event instanceof NavigationEnd)
.map(() => this.activatedRoute)
.map((route) => {
while (route.firstChild) route = route.firstChild;
return route;
})
.filter((route) => route.outlet === 'primary')
.mergeMap((route) => route.data)
.subscribe((event) => this.titleService.setTitle(event['title']));
}
}
回答by CROSP
You can achive this by subscribing to Router events
as follows
您可以通过订阅Router events
以下内容来实现此目的
private setTitleFromRouteData(routeData) {
if (routeData && routeData['title']) {
this.pageTitle = routeData['title'];
} else {
this.pageTitle = 'No title';
}
}
private getLatestChild(route) {
while (route.firstChild) {
route = route.firstChild;
}
return route;
}
private subscribeToRouteChangeEvents() {
// Set initial title
const latestRoute = this.getLatestChild(this.activeRoute);
if (latestRoute) {
this.setTitleFromRouteData(latestRoute.data.getValue());
}
this.router.events.pipe(
filter(event => event instanceof NavigationEnd),
map(() => this.activeRoute),
map((route) => this.getLatestChild(route)),
filter((route) => route.outlet === 'primary'),
mergeMap((route) => route.data),
).subscribe((event) => {
this.setTitleFromRouteData(event);
});
}
I have written a complete tutorial on this matter - https://medium.com/@CROSP/page-specific-dynamic-angular-components-using-child-routes-40f3cc47ce10
我已经写了一个关于这个问题的完整教程 - https://medium.com/@CROSP/page-specific-dynamic-angular-components-using-child-routes-40f3cc47ce10
回答by Prithivi Raj
use title service in browser platform to change the title dynamically. refer this link for more information
使用浏览器平台的标题服务动态更改标题。请参阅此链接以获取更多信息
app.module.ts
app.module.ts
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 { }
app.component.ts
app.component.ts
// Import the native Angular services.
import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
@Component({
selector: 'app-root',
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 );
}
}
回答by Saurabh Tiwari
Based on OP's requirement, it seems OP needs to bind a string property to the page.
根据 OP 的要求,OP 似乎需要将字符串属性绑定到页面。
In your component have a property. Since its a fix string you can initialize it on each component like:
在您的组件中有一个属性。由于它是一个修复字符串,您可以在每个组件上对其进行初始化,例如:
public title:string = 'About me';
and in your HTML just:
在你的 HTML 中:
<h1>{{title}}</h1>
<h1>{{title}}</h1>
Update:
更新:
Since it is to be bound to a constant header component, you will have to emit
an event from each component using EventEmitter
and listen to it across multiple components in your app and accordingly update the title property.
由于它要绑定到一个恒定的标头组件,因此您必须emit
使用来自每个组件的事件,EventEmitter
并在应用程序中的多个组件中监听它,并相应地更新 title 属性。
As suggested by Aamir in comments: You can have a service, wherein you can create an Observable and then update its next
value in each component. The observable can then be subscribed in the header
component to update the title
property.
正如 Aamir 在评论中所建议的那样:您可以拥有一个服务,您可以在其中创建一个 Observable,然后next
在每个组件中更新其值。然后可以在header
组件中订阅 observable以更新title
属性。