Ros*_*Dil 3 typescript angular-routing angular
我有一个场景,比如正在开发的应用程序中有一个员工列表。当我单击一名员工姓名时,它会导航到该员工的详细信息。每当我导航到每个员工的详细信息时,我的浏览器标题应显示类似\xe2\x80\x9cEmployee Name: Employee Number" 的信息。这样标题应根据员工而变化。
\n假设我也有部门列表,并且应该发生同样的事情;如果我导航到部门组件浏览器标题应显示类似\xe2\x80\x9cDepartment Name: Department Number\xe2\x80\x9d 的信息。
\n请建议如何以通用方式实现此目的,而不是在每个组件中设置标题。
\nAngular 提供了 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)
| 归档时间: |
|
| 查看次数: |
6366 次 |
| 最近记录: |