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

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?
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
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With