要在Angular 8中导航后不更改标题,可以使用Angular的Title
服务来设置页面标题,并在导航时保存当前标题。
首先,确保在组件中注入Title
服务:
import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
@Component({
selector: 'app-root',
template: `
`
})
export class AppComponent {
constructor(private titleService: Title) {}
navigateToPage1() {
this.titleService.setTitle('Page 1');
// 在这里导航到Page 1的路由
}
navigateToPage2() {
this.titleService.setTitle('Page 2');
// 在这里导航到Page 2的路由
}
}
然后,在每个页面组件的构造函数中获取当前标题并在组件销毁时恢复它:
import { Component, OnDestroy } from '@angular/core';
import { Title } from '@angular/platform-browser';
@Component({
selector: 'app-page1',
template: 'Page 1'
})
export class Page1Component implements OnDestroy {
private originalTitle: string;
constructor(private titleService: Title) {
this.originalTitle = this.titleService.getTitle();
}
ngOnDestroy() {
this.titleService.setTitle(this.originalTitle);
}
}
@Component({
selector: 'app-page2',
template: 'Page 2'
})
export class Page2Component implements OnDestroy {
private originalTitle: string;
constructor(private titleService: Title) {
this.originalTitle = this.titleService.getTitle();
}
ngOnDestroy() {
this.titleService.setTitle(this.originalTitle);
}
}
这样,当导航到Page 1或Page 2时,页面标题将会更改为相应的标题,并在离开时恢复原始标题。