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}
];
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
});
}
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. :)