Angular中如何移除错误页面的header和footer且不影响其他页面
你之前修改路由时报错是因为语法不规范:children 数组结束的括号后缺少逗号,同时在包含children字段的路由节点下直接平级写component字段的写法不符合Angular路由配置规则,才会触发TS1005的逗号缺失报错。
要实现错误页隐藏头尾、其他页面保留的需求,有两种常用方案:
方案一:路由标记法(改动最小,适合简单场景)
无需调整现有路由层级,通过路由自定义参数标记是否隐藏头尾:
- 修改路由配置,给错误页添加自定义标记
const routes: Routes = [ {path:'',component:HomeComponent}, {path:'CurrencyCalculator',component:CurrencyCalculatorComponent}, {path:'**',component:ErrorPageComponent, data: { hideHeaderFooter: true }} ];
- 修改
app.component.ts,监听路由变化获取标记
import { Component } from '@angular/core'; import { Router, NavigationEnd, ActivatedRoute } from '@angular/router'; import { filter, map } from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { // 控制头尾显隐的标记 hideHeaderFooter = false; constructor(private router: Router, private activatedRoute: ActivatedRoute) { this.router.events.pipe( // 只监听路由跳转结束事件 filter(event => event instanceof NavigationEnd), // 递归获取最深层路由的自定义参数 map(() => { let route = this.activatedRoute.root; while (route.firstChild) { route = route.firstChild; } return route.snapshot.data?.['hideHeaderFooter'] || false; }) ).subscribe(hide => { this.hideHeaderFooter = hide; }); } }
- 修改
app.component.html,给头尾添加显隐判断
<app-navigation *ngIf="!hideHeaderFooter"></app-navigation> <router-outlet></router-outlet> <app-footer *ngIf="!hideHeaderFooter"></app-footer>
方案二:嵌套路由布局法(结构清晰,适合多布局场景)
如果后续还有其他页面需要自定义布局,推荐用嵌套路由拆分公共布局:
- 新建
LayoutComponent作为公共布局组件,内容为:
<app-navigation></app-navigation> <router-outlet></router-outlet> <app-footer></app-footer>
- 调整路由配置,普通页面作为公共布局的子路由,错误页与公共布局平级
const routes: Routes = [ { path: '', component: LayoutComponent, children: [ {path:'',component:HomeComponent}, {path:'CurrencyCalculator',component:CurrencyCalculatorComponent}, ] }, {path:'**',component:ErrorPageComponent} ];
- 把原
app.component.html的内容替换为仅保留路由出口即可:
<router-outlet></router-outlet>
内容的提问来源于stack exchange,提问作者joe
相关产品推荐
相关产品推荐

