以角度2动态更改标题字符串

Smo*_*son 11 javascript typescript angular

在我的应用程序中我试图根据我所在的页面动态更改标题组件中的标题,因此在我的标题组件中我想使用

<h1>{{title}}</h1>
Run Code Online (Sandbox Code Playgroud)

我希望它根据我所在的页面进行更改.现在标题已修复,因此它位于每个页面上

下面是我试图改变的图像 在此输入图像描述

基本上,如果我在主页上我希望它说回家,然后如果我在一个关于页面,我希望它改为约...

我不确定如何解决这个问题,我研究的所有内容都是更改<head></head>标签中的标题

Aam*_*han 16

您可以创建专用于更新标题组件中标题的服务.只需在头部组件中注入服务并订阅专用的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');
}
Run Code Online (Sandbox Code Playgroud)

工作演示

  • 有效,但总是抛出错误:`ERROR Error: "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.` - 知道如何解决这个问题吗? (2认同)