如何检测Angular2中的路径

时间:2017-04-10 13:19:10

标签: javascript html angular typescript

我试图在这里做点什么:AngularJS show div based on url/condition

<span id="page-locator" *ngIf="location.path() == '/overview'">test</span>

但它没有用。

如何在Angular2中实现这一目标?

感谢。

3 个答案:

答案 0 :(得分:3)

看起来您正在尝试使用Angular路由器的路径,对吗?如果是这样,您可以将Router服务注入您的组件并在您的视图中使用它:

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

export class SomeComponent {
    constructor(public router: Router) { }
}

然后在您的组件模板中,您可以通过以下方式访问当前路由器URL:

<span id="page-locator" *ngIf="router.url === '/overview'">test</span>

答案 1 :(得分:0)

window.location是您获取信息的地方!

对于绝对路径,你可以这样:

constructor(location:Location) {
  console.log(location.prepareExternalUrl(location.path()));
}

答案 2 :(得分:0)

尝试以下解决方案:

location: any;
constructor(private _router: Router) { 
      _router.events.subscribe((data:any) => { this.location = data.url; });
}

数据是一个对象,我们需要该对象中包含的url属性。

<span id="page-locator" *ngIf="location == '/overview'">test</span>