在我的应用程序中,我试图根据我所在的页面动态更改标题组件中的标题,所以在我的标题组件中,我想使用
<h1>{{title}}</h1>
我希望它根据我所在的页面而改变。现在标题是固定的,所以它在每个页面上
基本上,如果我在主页上,我希望它显示主页,然后如果我在关于页面上,我希望它更改为关于..
不确定我该怎么做,我研究的所有内容都是为了更改 <head></head>
中的标题。标签
最佳答案
您可以创建一个专门用于更新标题组件中的标题的服务。只需在您的 header 组件中注入(inject)服务并订阅专用的 BehaviorSubject .然后您可以在您拥有的任何组件中注入(inject)此服务,并使用该组件的 setTitle 方法,该方法将更新 header 组件中的标题。看看下面的代码
//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');
}
关于javascript - 以 Angular 2 动态更改标题字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47257167/