Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current active child component in Angular 6

I'm using Angular 6.

I have created a deep routing in my application where app.module a declaration with component AdminLayout

@NgModule({
  declarations: [
    AppComponent,
    AdminLayoutComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    RouterModule.forRoot([]),
    ComponentsModule,
  ]
});

and further AdminLayoutComponent is a module which imports all other modules inside it.

@NgModule({
  imports: [
    ...
    DashboardModule
  ],
  declarations: []
})
export class AdminLayoutModule { }

ComponentsModule is imported in AppModule in which I want to get the currently active component or the URL.

So, Inside a component of ComponentsModule, I'm doing it like this:

constructor(
  private route: ActivatedRoute
) { }

ngOnInit() {
  console.log(this.route);
}

which consoles like

enter image description here

Here, it has the component > name as AdminLayoutComponent whereas I have loaded DashboardComponent.

How can I get the currently active component name or the URL?

like image 701
Anuj TBE Avatar asked Aug 18 '26 16:08

Anuj TBE


1 Answers

You can use Router service to get current url , the url change in every navigation so you can subscribe to route events to keep update

import {  Router } from '@angular/router';

component

constructor( private _router: Router,) { ...}

ngOnInit() {
   this.router.events.subscribe(e => {
      if (e instanceof NavigationStart) {
        console.log(e.url);
        console.log(this.router.routerState.root.snapshot.firstChild); // active component
        console.log(this.router.routerState.root.snapshot.data); // route data
        console.log(this.router.routerState.root.snapshot.routeConfig); // routes list
      }
    });
}
like image 79
Muhammed Albarmavi Avatar answered Aug 20 '26 07:08

Muhammed Albarmavi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!