How to catch routes in *ngIf

余生长醉 提交于 2020-02-01 19:00:13

问题


So I want to make an anchor element on my Header disappear when a specific page is hit. How can I catch the url in the *ngIf when that page is hit.

I have a header which will remain same for all pages. Just need to hide an anchor element when I am routed at /home. How to catch this "/home" in *ngIf?

*ngIf = "href='/home'" is not working. Any alternatives?


回答1:


//mycomponent.component.ts
class MyComponent {
    constructor(private router: Router){

    }
}

//mycomponent.component.html
    <div *ngIf="router.url === '/some/route'">

    </div>



回答2:


I came to this page because I had the same issue than Ravy but the proposed solutions were not ok for me.

The accepted answer is not working if you are using route path with query params.

Here's the solution I use:

//mycomponent.component.ts
class MyComponent {
constructor(public router: Router){

}
}

//mycomponent.component.html
<div *ngIf="router.isActive('/some/route')">

</div>



回答3:


You can check current route path using location.path() method and decide it whether /home route is activated or not.

*ngIf="isHomeRouteActivated()"

Code

//Inject `Location` dependency before using it
isHomeRouteActivated(): boolean{
    //Find more better way to do it.
    return this.location.path().indexOf('/home') > -1;
}



回答4:


// mycomponent.component.ts

class MyComponent {
    constructor(public router: Router){

    }
}

// mycomponent.component.html

<div *ngIf="this.router.url === '/some/route'">

</div>


来源:https://stackoverflow.com/questions/44429276/how-to-catch-routes-in-ngif

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!