How to show an element only on a specific route?

Viewed 206

I have a Navbar with some basic login and signup routing, but the thing is, on the home page ('/') i have an about us section which i don't want to show when i'm in the login('/login') or the signup('/signup') page. So how can i show that section only on the route('/')?

2 Answers

You can use the router events combined with the resolved urlAfterRedirects inside the events object:

export class NavComponent {
  readonly showAbout$ = this.router.events.pipe(
    filter((event) => event instanceOf NavigationEnd)
    map((event) => this.canShowAbout(event.urlAfterRedirects)),
    startWith(this.canShowAbout(this.router.url))
  )

  constructor(readonly router: Router) {}

  canShowAbout(url: string): boolean {
    return ['/login', '/signup'].every((path) => !url.startsWith(path)
  }
}

and in your component use the async pipe:

<nav>
  <a routerLink="/home">Home</a>
  <a *ngIf="showAbout$ | async" routerLink="/about">
    About
  </a>
</nav>

In .ts file

export class Page {
  __URL:string = ""
  constructor(router: Router) {
   console.log(router.url); // This will print the current url
   this.__URL = this.router.url;
  }
}

And in you .html file, You can make use of *ngIf

<div *ngIf="__URL === '/'">
 // Render whatever you want
</div>

#Edit

Try Location instead of Router

import { Location } from '@angular/common';

export class AppComponent implements OnInit {
  constructor(private location: Location) {}

  ngOnInit(){
    console.log(this.location.path());
  }

}

Feel free to see docs

In case it does not work , Try the following

 this.router.events
  .pipe(
    filter(e => e instanceof NavigationEnd)
  )
  .subscribe( (navEnd:NavigationEnd) => {
    console.log(navEnd.urlAfterRedirects);
  });
Related