要在特定的动态slug上不显示页头和页脚,可以使用Angular的路由守卫来实现。以下是一个示例解决方案:
guards
的文件夹,并在其中创建一个名为auth.guard.ts
的文件。import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable | Promise | boolean | UrlTree {
// 在这里检查动态slug是否需要隐藏页头和页脚
const slug = next.paramMap.get('slug');
const hideHeaderFooterSlugs = ['example-slug-1', 'example-slug-2']; // 在这里添加需要隐藏页头和页脚的slug
if (hideHeaderFooterSlugs.includes(slug)) {
return false; // 不允许访问页面
}
return true; // 允许访问页面
}
}
import { AuthGuard } from './guards/auth.guard';
// ...
@NgModule({
// ...
providers: [AuthGuard],
// ...
})
export class AppModule { }
/pages/:slug
:import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PageComponent } from './page/page.component';
import { AuthGuard } from './guards/auth.guard';
const routes: Routes = [
// ...
{
path: 'pages/:slug',
component: PageComponent,
canActivate: [AuthGuard] // 使用AuthGuard来保护页面
},
// ...
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
*ngIf
指令来根据AuthGuard返回的结果来显示或隐藏页头和页脚。
// page.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-page',
templateUrl: './page.component.html',
styleUrls: ['./page.component.scss']
})
export class PageComponent implements OnInit {
hideHeaderFooter: boolean = false;
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
const slug = this.route.snapshot.paramMap.get('slug');
const hideHeaderFooterSlugs = ['example-slug-1', 'example-slug-2']; // 在这里添加需要隐藏页头和页脚的slug
if (hideHeaderFooterSlugs.includes(slug)) {
this.hideHeaderFooter = true;
}
}
}
通过以上步骤,你可以根据动态slug的值来决定是否显示页头和页脚。如果slug在hideHeaderFooterSlugs
数组中,页头和页脚将不会显示。否则,它们将正常显示。