[英]How to detect path in Angular2
I'm trying to make something like here: AngularJS show div based on url/condition 我想尝试做类似的事情: AngularJS根据url / condition显示div
<span id="page-locator" *ngIf="location.path() == '/overview'">test</span>
but it doesn't work. 但它不起作用。
How can I achieve this in Angular2? 我怎样才能在Angular2中实现这一目标?
Thanks. 谢谢。
It looks like you're trying to use the path of the Angular router, correct? 看起来你正试图使用Angular路由器的路径,对吗? If so, you can inject the
Router
service into your component and use that in your view: 如果是这样,您可以将
Router
服务注入组件并在视图中使用它:
import { Router } from '@angular/router';
export class SomeComponent {
constructor(public router: Router) { }
}
Then in your component template you can access the current router url via: 然后在组件模板中,您可以通过以下方式访问当前路由器URL:
<span id="page-locator" *ngIf="router.url === '/overview'">test</span>
window.location
is where you can get your information! window.location
是您可以获取信息的地方!
for an absolute path you can go this way : 对于绝对路径,你可以这样:
constructor(location:Location) {
console.log(location.prepareExternalUrl(location.path()));
}
Try the following solution : 尝试以下解决方案:
location: any;
constructor(private _router: Router) {
_router.events.subscribe((data:any) => { this.location = data.url; });
}
The data is an object and we need the url property contained in that object. 数据是一个对象,我们需要该对象中包含的url属性。
<span id="page-locator" *ngIf="location == '/overview'">test</span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.