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

后端 未结 2 1653
时光取名叫无心
时光取名叫无心 2021-01-06 06:14

This my ap.component.html






        
相关标签:
2条回答
  • 2021-01-06 06:58

    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
        });
    }
    
    0 讨论(0)
  • 2021-01-06 06:59

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

    0 讨论(0)
提交回复
热议问题