Get current active child component in Angular 6

6.4k Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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
      }
    });
}
0
On
public ngOnInit() {
  this.helloChild()
  this.router.events.subscribe((event) => {
    if (event instanceof NavigationEnd) {
      this.helloChild()
    }
  })
}

private helloChild() {
  const firstChild = this.route.snapshot.firstChild
  console.log('firstChild', firstChild)
}