【问题标题】:How to get current component name in Angular2如何在Angular2中获取当前组件名称
【发布时间】:2017-12-27 14:27:08
【问题描述】:

当用户点击促销页面时,我想在 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;   
  } 
}

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

【问题讨论】:

  • 尝试激活路由或路由器工作

标签: angular


【解决方案1】:

要获取当前激活的路由,可以注入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";
      });
  }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    • 2016-05-09
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 2011-09-08
    相关资源
    最近更新 更多