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

谁说我不能喝 提交于 2019-12-01 12:33:48

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

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