DEV Community

Deepa Chaurasia for This is Angular

Posted on • Edited on

How to show or hide component on basis of url in Angular.

As a Frontend developer,You come across a situation where you have to show a component only if you navigate to dashboard,or your login component.For rest you must hide.

How are you going to manage all of this in angular??

Well Angular provides you a various events and properties of router that you can use to track on which router user is currently at.

We will be discussing NavigationEnd event of Angular route

What is Navigation End??

An event triggered when a navigation ends successfully.

How to Use??

Image description

  • Inside constructor you subscribe to router events.
  • Then you will check subscribed val is an instance of Navigation End or not .
  • If yes then you will use that subscribed value and use value.url to find the url where user has navigated currently and put logic inside.
  • At last you will write your logic according to value.url

In the example above I have wrote logic to not show header on login , else on all other components whether dashboard,or any other headers will be visible.

My app.component.html looks like this

Image description

*Here you can see I am showing header only if "showHeader" property is true
*

My app.component.ts looks like this

Image description

Now If i click on submit button it will route to 'dashboard'
and shows dashboard component.

Image description

*Therefore header component becomes visible *

Image description

The working respository for reference
https://stackblitz.com/edit/angular-ivy-atods7?file=src/app/app.component.ts

Github Link
https://github.com/deepa314/angular-ivy-atods7.git

I hope it help you guys :)
If you like please like ,share and subscribe

Top comments (0)