繁体   English   中英

如何在Angular2中获取当前组件名称

[英]How to get current component name in Angular2

我想在用户点击促销页面时在Angular2中隐藏页眉和页脚。

https://example.com/promo

我的应用程序组件如下:

  <login-bar></login-bar>
  <banner *ngIf="showComponent()"></banner>
  <navbar *ngIf="showComponent()"></navbar>
  <router-outlet></router-outlet>
  <footer *ngIf="showComponent()"></footer>

如果用户在页面上:/ promo我想隐藏标题,导航栏和页脚组件。

在我的代码中,我有:

export class AppComponent {   constructor(
      private router:Router

  ) {}

  showComponent(): Boolean {
    ****
    How do I check the current route?
    ****
    var currentRoute = ** enter magic here **
    return (currentRoute === "promo") ? true : false;   
  } 
}

所以我的问题是,找到当前所在页面/路线以便显示或隐藏组件的最佳方法是什么?

要获取当前激活的路由,可以注入ActivatedRoute服务。 这将使您可以访问当前路线URL的Observable。

export class AppComponent {

  // Bind to this:
  isPromo = false;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
      route.url.subscribe(segments => {
          this.isPromo = segments[0].path === "promo";
      });
  }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM