如何知道Angular 5及更高版本的路由器出口中加载了哪个组件 [英] How to Know Which component is loaded in router-outlet in Angular 5 and above

查看:41
本文介绍了如何知道Angular 5及更高版本的路由器出口中加载了哪个组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的ap.component.html

This my ap.component.html

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

如何知道路由器出口中加载了哪个组件,然后根据标题或正文添加类组件。

How to know which component is loaded in Router outlet and then add a class on header or body depending on the component.

就像加载Home一样,在主体上添加一个home类。或404页,然后在正文上找不到类

Just Like if Home is loaded then add a home class on the body. or if 404 page then notfound class on 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}
];


推荐答案

header.component.html

header.component.html

<nav class="navbar navbar-expand-lg navbar-dark bg-primary py-3" [ngClass]="{'isNotFound': isNotFound, 'isHome': isHome}" id="mainNav">
  <div class="container">

路由

...
  { path: 'services' , component: ServicesComponent },
  { path: '', pathMatch: 'full', redirectTo: '/' },
  { path: '**', component: NotfoundComponent , data: { status : 'notfound'}}
];

header.component.ts

header.component.ts

 ngOnInit() {
    this.isNotFound = false;
    this.router.events
        .filter(e => e instanceof NavigationEnd)
        .subscribe(event => {
          this.isNotFound = this.route.firstChild.data._value.status;
          if (this.isNotFound) {
            this.isNotFound = true;
          }
        });
  }

首先,我仅将数据发送到未找到的组件,然后在标头组件上接收然后使用 ngClass 在位于路由器出口外部的导航栏中添加一个类。

First, I sent data only to the notfound component then received it on header component then using ngClass add a class on the navbar which is outside router outlet.

这是我解决的方法,尽管感谢所有建议。 :)

This is how i solved it, Though thanks for all the advice. :)

这篇关于如何知道Angular 5及更高版本的路由器出口中加载了哪个组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆