特定组件的动态标题 Angular
Dynamic title for specific component Angular
我在 Java Spring 服务器端使用 Angular 8。现在这是我的路线
{
component: IndexComp
path: "index"
},
{
component: BlogComp
path: "blog"
},
{
component: ProductComp
path: "product/:id"
},
默认标题为“商店”,用于博客和索引页面。但是在产品页面中,标题来自服务器(可能 Iphone7、Iphone8、裙子...取决于来自服务器的数据)。我想知道如何更改产品页面的标题,tks
看看 @angular/platform-browser
中的 Title
。
可以在组件中注入使用setTitle('You title string here')
例如:
constructor(private readonly titleService: Title) {
const title = 'Shop'; // get title data from the server
this.titleService.setTitle(title);
}
UPD: 在此基础上,您可以在任何地方制作它:在 resolver/component/service 等
UPD:根据路线:你可以在AppComponent中做类似的事情,例如
constructor(private readonly titleService: Title,
private readonly router: Router) {
this.router.events.subscribe(route => {
if (route instanceof NavigationEnd && route.urlAfterRedirects !== '/product') {
const title = 'Dynamic Title String Here';
this.titleService.setTitle(title);
} else {
const title = 'Default Title String Here';
this.titleService.setTitle(title);
}
});
}
您可以使用这种最简单的路由方式,如下所示...
{
path: 'Here/Your/Path',
component: YourComponent,
data: { title: "This is my title" },
canActivate: [AuthGuardService]
}
- 在你的组件中
this.route.data.subscribe(res => this.appComponent.title = res['title']);
- 在 App 组件中
//initialize variable
title: string = '';
在页面的 header 中使用此标题变量。
希望对您有所帮助。 :)
我在 Java Spring 服务器端使用 Angular 8。现在这是我的路线
{
component: IndexComp
path: "index"
},
{
component: BlogComp
path: "blog"
},
{
component: ProductComp
path: "product/:id"
},
默认标题为“商店”,用于博客和索引页面。但是在产品页面中,标题来自服务器(可能 Iphone7、Iphone8、裙子...取决于来自服务器的数据)。我想知道如何更改产品页面的标题,tks
看看 @angular/platform-browser
中的 Title
。
可以在组件中注入使用setTitle('You title string here')
例如:
constructor(private readonly titleService: Title) {
const title = 'Shop'; // get title data from the server
this.titleService.setTitle(title);
}
UPD: 在此基础上,您可以在任何地方制作它:在 resolver/component/service 等
UPD:根据路线:你可以在AppComponent中做类似的事情,例如
constructor(private readonly titleService: Title,
private readonly router: Router) {
this.router.events.subscribe(route => {
if (route instanceof NavigationEnd && route.urlAfterRedirects !== '/product') {
const title = 'Dynamic Title String Here';
this.titleService.setTitle(title);
} else {
const title = 'Default Title String Here';
this.titleService.setTitle(title);
}
});
}
您可以使用这种最简单的路由方式,如下所示...
{
path: 'Here/Your/Path',
component: YourComponent,
data: { title: "This is my title" },
canActivate: [AuthGuardService]
}
- 在你的组件中
this.route.data.subscribe(res => this.appComponent.title = res['title']);
- 在 App 组件中
//initialize variable
title: string = '';
在页面的 header 中使用此标题变量。
希望对您有所帮助。 :)