如何在 Angular 8 的浏览器选项卡中动态设置页面标题?

Ros*_*Dil 3 typescript angular-routing angular

我有一个场景,比如正在开发的应用程序中有一个员工列表。当我单击一名员工姓名时,它会导航到该员工的详细信息。每当我导航到每个员工的详细信息时,我的浏览器标题应显示类似\xe2\x80\x9cEmployee Name: Employee Number" 的信息。这样标题应根据员工而变化。

\n

假设我也有部门列表,并且应该发生同样的事情;如果我导航到部门组件浏览器标题应显示类似\xe2\x80\x9cDepartment Name: Department Number\xe2\x80\x9d 的信息。

\n

请建议如何以通用方式实现此目的,而不是在每个组件中设置标题。

\n

Leo*_*ire 7

Angular 提供了 TitleService,允许您在任何给定时间更改页面的标题。

是这里:

import { Title } from '@angular/platform-browser';
Run Code Online (Sandbox Code Playgroud)

无论是在自定义服务中,您都可以监听路由更改、获取最底层的路由并根据路由器上传递的数据更改标题。

public title: string = '';

constructor(private router: Router,  
    private activatedRoute: ActivatedRoute,  
    private titleService: Title) {}  

ngOnInit() {  
    this.router.events.pipe(  
        filter(event => event instanceof NavigationEnd),  
    ).subscribe(() =>
        this.titleService.setTitle(this.title));
}  

getChild(activatedRoute: ActivatedRoute) {  
    if (activatedRoute.firstChild) {  
        return this.getChild(activatedRoute.firstChild);  
    } else {  
        return activatedRoute;  
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以为每个组件设置所需的标题。

constructor(private customService: CustomService) {
    this.customService.title = 'Whatever you want';
}
Run Code Online (Sandbox Code Playgroud)

  • 只需像我说的那样创建一个服务,并具有设置标题字段的功能。然后,在每个组件中,您需要设置所需的标题,并且在 NavigationEnd 上,服务将更新浏览器的标题。PS:编辑我的答案以满足要求。 (2认同)