如何知道 Angular 5 及以上版本的 router-outlet 中加载了哪个组件

2023-12-10

这是我的 ap.component.html

<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>

如何知道 Router Outlet 中加载了哪个组件,然后根据组件在 header 或 body 上添加一个类。

就像加载 Home 后在 body 上添加一个 home 类一样。或者如果 404 页面则在 body 上找不到类

我的路线

const routes: Routes = [
  { path: '' , component: HomeComponent},
  { path: 'directory' , component: DirectoryComponent },
  { path: 'directory/:slug' , component: DirectorySingleComponent },
  { path: 'pricing' ,component: PricingComponent },
  { path: 'services' , component: ServicesComponent },
  { path: '', pathMatch: 'full', redirectTo: '/' },
  { path: '**', component: NotfoundComponent}
];

您需要在组件内部或基于变量处理此问题,您可以使用路由器的 url 属性来获取当前组件的 url

constructor(router: Router) {
this.router.events.subscribe((event: Event) => {
            console.log(event.url); //based on this change class
    });
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何知道 Angular 5 及以上版本的 router-outlet 中加载了哪个组件 的相关文章

随机推荐