Frontend developers often need to conditionally display certain components based on the current route. For instance, you may want a header visible on a dashboard but hidden on a login page, with all other routes showing it.

What is the best approach in Angular for this?

Angular's router exposes several events and properties that allow you to monitor the user's current navigation state.

This guide focuses on the NavigationEnd event from the Angular router.

Understanding the NavigationEnd Event

This is an event that is emitted whenever a navigation lifecycle completes successfully.

Implementation Steps

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

  • Subscribe to the router events within the component's constructor.
  • Check if the emitted value is an instance of NavigationEnd.
  • If it is, access the url property on the event object to determine the route the user has navigated to, and apply your conditional logic based on that.
  • Finally, implement the specific logic you need using the value.url.

In the example provided, the logic hides the header on the login route while it remains visible on all other pages, such as the dashboard.

Here is what the app.component.html template looks like:

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

Notice that the header is rendered only when the showHeader property is set to true.

The corresponding app.component.ts file is:

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

When the submit button is clicked, the app routes to 'dashboard' and the dashboard component is rendered.

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

As a result, the header component becomes visible.

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

You can find a working demo for reference here:
https://stackblitz.com/edit/angular-ivy-atods7?file=src/app/app.component.ts

The source code is also available on GitHub:
https://github.com/deepa314/angular-ivy-atods7.git

Hopefully, this guide proves helpful for your projects.