如何在Angular Router中切换路由时动态修改页面标题
实现路由切换时动态修改应用主标题
方法一:根据路由路径直接匹配标题
1. 修改 default.component.ts
引入路由依赖,新增标题变量并监听路由切换事件:
import { AfterViewInit, Component, ViewChild } from '@angular/core'; import { BreakpointObserver } from '@angular/cdk/layout'; import { MatSidenav } from '@angular/material/sidenav'; import { Router, NavigationEnd } from '@angular/router'; import { filter } from 'rxjs/operators'; @Component({ selector: 'app-default', templateUrl: './default.component.html', styleUrls: ['./default.component.css'] }) export class DefaultComponent implements AfterViewInit { @ViewChild(MatSidenav) sidenav!: MatSidenav; currentTitle = ''; constructor(private observer: BreakpointObserver, private router: Router) { // 只监听路由切换完成的事件 this.router.events.pipe( filter(event => event instanceof NavigationEnd) ).subscribe(() => { // 根据当前路由路径设置对应标题 switch (this.router.url) { case '/app/dashboard': this.currentTitle = '仪表盘'; break; case '/app/statistic': this.currentTitle = '统计'; break; default: this.currentTitle = '首页'; } }); } ngAfterViewInit(): void { this.observer.observe(['(max-width:959px)']).subscribe((res) => { if (res.matches) { this.sidenav.mode = 'over'; this.sidenav.close() } else { this.sidenav.mode = 'side'; this.sidenav.open() } }) } }
2. 修改 default.component.html
将标题与组件中的 currentTitle 变量绑定:
<h1 class="title">My first application - {{ currentTitle }}</h1>
方法二:通过路由配置的 data 字段设置(更优雅易扩展)
这种方式无需在组件中硬编码路由路径,新增页面时只需修改路由配置即可。
1. 修改路由配置文件
在对应路由的 data 属性中定义页面标题:
import { Routes } from '@angular/router'; import { DefaultComponent } from './default/default.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { StatisticComponent } from './statistic/statistic.component'; const routes: Routes = [ { path: 'app', component: DefaultComponent, children: [ { path: 'dashboard', component: DashboardComponent, data: { title: '仪表盘' } // 配置页面标题 }, { path: 'statistic', component: StatisticComponent, data: { title: '统计' } // 配置页面标题 } ] } ]; export const AppRoutes = routes;
2. 更新 default.component.ts 的路由监听逻辑
从路由的 data 中读取标题:
// 其他导入代码保持不变 constructor(private observer: BreakpointObserver, private router: Router) { this.router.events.pipe( filter(event => event instanceof NavigationEnd) ).subscribe(() => { // 获取当前激活的子路由 const activeRoute = this.router.routerState.root.firstChild; // 提取路由data中的标题,默认显示"首页" this.currentTitle = activeRoute?.data['title'] || '首页'; }); } // 其他代码保持不变
3. 绑定标题到模板
和方法一第二步一致:
<h1 class="title">My first application - {{ currentTitle }}</h1>
内容的提问来源于stack exchange,提问作者Daemes
相关产品推荐
相关产品推荐

