Angular 仅替换部分标题元素
我正在寻找一种在Angular中使用title服务替换title元素部分的方法。所以基本上,我有一个当前页面的Angular 仅替换部分标题元素,angular,typescript,Angular,Typescript,我正在寻找一种在Angular中使用title服务替换title元素部分的方法。所以基本上,我有一个当前页面的WebApp |标题。每当我导航到不同的路线时,我想替换“当前页面标题”的部分 如何做到这一点?Angular为此提供了一个名为Title的可注入服务。可以找到关于如何使用该服务的官方指南 下面是一个演示如何验证此概念并动态更改路由标题的示例。您可以使用 在app.component.ts中 export class AppComponent { title = "WebA
WebApp |标题
。每当我导航到不同的路线时,我想替换“当前页面标题”的部分
如何做到这一点?Angular为此提供了一个名为
Title
的可注入服务。可以找到关于如何使用该服务的官方指南
下面是一个演示如何验证此概念并动态更改路由标题的示例。您可以使用
在app.component.ts中
export class AppComponent {
title = "WebApp | ";
public constructor(private titleService: Title ) { }
ngOnInt(){
this.setTitle( 'Something Else' );
}
public setTitle( newTitle: string) {
this.titleService.setTitle( title + newTitle );
}
}
或
在app.component.html中(根组件)
WebApp |当前页面的标题
我已经这样做了。我不想这样做;我想在index.html
元素中设置WebApp。@如果你的angular应用程序是一个单页应用程序,基本上这是添加到index.htmlI中的title标记中的,那么我不想在app.component中设置该部分,我只想在app.component上或使用TitleService的任何地方替换部分内容。@rpd可能是您可以使用title srvice中的getTitle()
,获取当前标题并替换字符
后不需要的字符串
export class AppComponent {
title = "";
public constructor(private titleService: Title ) { }
ngOnInt(){
this.title = this.titleService.getTitle();
}
public setTitle( newTitle: string) {
let fistPart = this.title.substring(0, this.title.lastIndexOf('|'));
this.titleService.setTitle( fistPart + newTitle );
}
}
<title>WebApp | title of the current page</title>