2017-04-10 89 views
1

路上我试图让一些喜欢这里:AngularJS show div based on url/condition如何检测Angular2

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

,但它不工作。

我如何在Angular2中实现这一点?

谢谢。

+1

如果你正在寻找对于当前页面,然后检查此链接:H [我是否获取Angular 2中当前页面的绝对路径?](http://stackoverflow.com/questions/37517183/how-do-i-get-the-absolute -path-of-the-current-page-in-angular-2) – sameer

+0

我试图让ngIf工作,但是谢谢。 –

回答

1

它看起来像你试图使用Angular路由器的路径,正确吗?如果是这样,你可以注入Router服务为您的组件和使用,在您的视图:

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

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

然后在你的组件模板中,您可以通过访问当前路由器网址:

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

'overvierw'只是整个网址的一部分... –

+1

您可以在该场景中使用'* ngIf =“router.url.indexOf('/ overview')> = 0”'来确定url是否包含路线也是如此。 – DRiFTy

+0

怎么......我忘了indexOf()...谢谢你的队友! –

0

window.location是你可以得到你的信息!

了绝对路径,你可以走这条路:

constructor(location:Location) { 
    console.log(location.prepareExternalUrl(location.path())); 
} 
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>