在 Angular 6 中获取当前活动的子组件

Get current active child component in Angular 6

我正在使用 Angular 6

我在我的应用程序中创建了一个深度路由,其中​​ app.module 一个包含组件 AdminLayout

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

而且 AdminLayoutComponent 是一个导入其中所有其他模块的模块。

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

ComponentsModuleAppModule 中导入,我想在其中获取当前活动的组件或 URL.

所以,在 ComponentsModule 的一个组件中,我是这样做的:

constructor(
  private route: ActivatedRoute
) { }

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

喜欢哪个游戏机

在这里,它有 component > name 作为 AdminLayoutComponent 而我加载了 DashboardComponent.

如何获取当前活动的组件名称或URL?

您可以使用 Router 服务获取当前 url ,每个导航中的 url 变化,因此您可以 订阅路线事件以保持更新

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

组件

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
      }
    });
}
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)
}