Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch routes in *ngIf

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?

like image 541
Ravy Avatar asked Jun 08 '17 07:06

Ravy


People also ask

How to access route parameters in Angular?

To access route parameters and query parameters in Angular, use the ActivatedRoute service. The ActivatedRoute service provides Observables through which we can subscribe to the values of route params and route query params.

What is wildcard route in Angular?

What is Wildcard Route in Angular? The Wildcard Route is basically used in Angular Application to handle the invalid URLs. Whenever the user enter some invalid URL or if you have deleted some existing URL from your application, then by default 404 page not found error page is displayed.

Can we use ngIf in router outlet?

so if you try to use *ngIf to conditionally disable and enable router-outlet to overcome the problem it does not work. One router-outlet will get registered and no matter what you do, next router-outlet will not respond to the route changes.


2 Answers

mycomponent.component.ts

import { Router } from '@angular/router'

class MyComponent {
    constructor(public router: Router) { }
}

mycomponent.component.html

<div *ngIf="router.url === '/some/route'">
    <!-- … -->
</div>
like image 102
Arvind Audacious Avatar answered Sep 21 '22 16:09

Arvind Audacious


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

import { Router } from '@angular/router'

class MyComponent {
    constructor(public router: Router) { }
}

mycomponent.component.html

<div *ngIf="router.isActive('/some/route')">
    <!-- … -->
</div>
like image 27
Jerome2606 Avatar answered Sep 18 '22 16:09

Jerome2606