How to Know Which component is loaded in router-outlet in Angular 5 and above

倖福魔咒の 提交于 2019-12-19 09:39:23

问题


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.

Just Like if Home is loaded then add a home class on the body. or if 404 page then notfound class on body

My Routing

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}
];

回答1:


You need to handle this inside the component or based on a variable, you can use url property of the router to get the current component url

constructor(router: Router) {
this.router.events.subscribe((event: Event) => {
            console.log(event.url); //based on this change class
    });
}



回答2:


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">

routing

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

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;
          }
        });
  }

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. :)



来源:https://stackoverflow.com/questions/49720164/how-to-know-which-component-is-loaded-in-router-outlet-in-angular-5-and-above

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!