Hiding the header on a specific route in Angular 6

Attempting to hide the header for only one specific route

Imagine having three different routes: route1, route2, and route3.

In this scenario, there is a component named app-header.

The goal is to make sure that the app-header component is hidden when the user navigates to route1, while being visible on the other two routes.

Despite coming across various similar questions on stackoverflow, none of the solutions seemed to work

Seeking some assistance from fellow developers!

Provided below is the relevant code snippet:

  • app.component.ts

    export class AppComponent implements OnInit {
        showHeader = true;
    
        constructor(
            private router: Router
        ) {
            this.router.events.subscribe(event => this.modifyHeader(event));
        }
    
        ngOnInit() {
        }
    
        modifyHeader(location) { // This method is called many times
            console.log(location.url); // This prints a loot of routes on console
            if (location.url === '/route1') {
                this.showHeader = false;
            } else {
                this.showHeader = true;
            }
        }
    }
    
    • app.component.html

      <app-header *ngIf="showHeader"></app-header>
      <router-outlet></router-outlet>
      

Angular version used: 6.1.4

Answer №1

When it comes to identifying a specific route and having a solution in mind within the app component, my suggestion would be to implement router event filtering as shown below:

export class AppComponent implements OnInit {
    showHeader = true;

    constructor(
        private router: Router
    ) {
        this.router.events.pipe(
            filter(e => e instanceOf NavigationEnd)
        ).subscribe(event => this.modifyHeader(event));
    }

    ngOnInit() {
    }

    modifyHeader(location) { // This function gets called multiple times
        console.log(location.url); // Outputs various routes to console
        if (location.url === '/route1') {
            this.showHeader = false;
        } else {
            this.showHeader = true;
        }
    }
}

Answer №2

Enhance the functionality of the router outlet

<router-outlet  (activate)="updateHeader()"></router-outlet>

Include this in your constructor

router; 
constructor(private _router: Router ) {
      this.router = _router;
    }

The updateHeader function

updateHeader() { // This method is triggered multiple times
        console.log(this.router.ur); // A list of routes will be displayed on the console
        if (this.router.ur === '/route1') {
            this.showHeader = false;
        } else {
            this.showHeader = true;
        }
    }

Please inform me if you encounter any difficulties.

Answer №3

Implementing the solution provided by @Krishna is incredibly efficient in terms of performance, as this observable remains subscribed since it is located within the root AppComponent of the application.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Delaying a request when a button is clicked in Angular using debounce

Struggling to figure out how to debounce an HTTP request using Rxjs after a button is clicked. What I want to accomplish is for the post to be delayed by x seconds after the button is clicked. btnClick() { this.loader = true; let send = "&qu ...

Implementing Authorization Headers in Angular for Secure HTTP Post Requests

I have been struggling to add Authorization Headers to a Post request after extensive research and trying various ways of adding headers to the request. I need to authenticate the post request of my Angular app to a Django server. headers2 = { "Conte ...

How can I retrieve the index of an element within a 2D array using JavaScript when the array is displayed on a webpage?

https://i.stack.imgur.com/GHx9p.png I am currently working on developing an Othello game board within an HTML page using Angular. The board itself is constructed from a 2D number array which I then display using the <table> tag on the webpage. Below ...

Is there a way to add an event listener to dynamically generated HTML using the v-html directive?

I have a string variable named log.htmlContent that contains some HTML content. This variable is passed into a div to be displayed using v-html. The particular div will only be displayed if log.htmlContent includes an img tag (http: will only be present in ...

Using Tailwind classes as a prop functions correctly, however, it does not work when directly applied

Here's a component snippet I'm working on: export const TextInput = ({ label, wrapperClassName = "", inputClassName = "", labelClassName = "", placeholder = "", ...props }: InputProps & Fiel ...

What is the process for running an Angular2 application on a mobile device during the development phase?

Currently, I am in the process of developing an Angular2 application. The application can be accessed by using ng s --open, which brings up the results on the browser through http://localhost:4200. In addition, I have set up a server on the same localhost ...

Encountering an ERROR with the message "Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError" while attempting to apply a filter to

My mat table includes a filter that utilizes chips to sort by multiple criteria. Upon my initial attempt to filter and save the criteria, I encountered an error called ExpressionChangedAfterItHasBeenCheckedError. The error message indicates a transition f ...

Angular's innerHTML dilemma

Within my Angular service, I have implemented three methods as shown below: public loadLiveChat() { let url: string; url = this.appConfig.config.liveAgent.liveAgentScriptUrl; this.dynamicallyLoadScript(url); ...

Angular 2 select does not recognize the selected option

In my Angular 2 code, I am using ngFor to populate a dropdown with options. I want a specific option at a certain index to be selected by default. Currently, I tried using [attr.selected]="i == 0" but it ends up selecting the last option instead of the fi ...

Refresh the page when scss file is saved

Exploring Angular 2 with the official Quick start guide has been a fun learning experience. The development dependencies specified in the package.json file enable live reload function by saving html files. In addition to utilizing Gulp and live reloading ...

Sharing data between two components in an Angular2-Meteor application

I am currently working with angular2-meteor. When attempting to transfer a value between two components (updating the value in the first component triggers an event in the second component where the new value is used), I have two methods available: The ...

Angular: Array in the template re-renders even if its length remains unchanged

Below is the template of a parent component: <ng-container *ngFor="let set of timeSet; index as i"> <time-shift-input *ngIf="enabled" [ngClass]="{ 'mini-times' : miniTimes, 'field field-last&ap ...

Occasionally encountering missing modules with Vscode and NestJs

This situation is really frustrating: I started a brand new NestJs project using the @nestjs/cli command. Everything was going smoothly at first. However, after adding a controller with nest generate controller mycontroller and installing types for jasmine ...

Tips for dynamically altering the data type of an object in Angular depending on a certain condition

I'm currently in the process of developing an online store and facing challenges with integrating a dynamic form system that can adapt based on the type of product being added to the store. For instance, if I select the 'Clothing' category, ...

Creating a form with multiple components in Angular 6: A step-by-step guide

I'm currently working on building a Reactive Form that spans across multiple components. Here's an example of what I have: <form [formGroup]="myForm" (ngSubmit)="onSubmitted()"> <app-names></app-names> <app-address> ...

Issue with MEAN app: unable to retrieve response from GET request

FETCH The fetch request is being made but no data is returned. There are no errors, just the fetch request repeating itself. app.get('/:shortUrl',async (req,res)=>{ try{ const shortUrl = await shorturl.findOne({ short: req.params.sh ...

The Gatsby + Typescript project is reporting that the module with the name "*.module.scss" does not have any exported members

I've recently gone through Gatsby's demo project in their documentation (which is long overdue for an update). I've carefully followed the instructions provided here: I've included an index.d.ts file in the /src directory of my project ...

What could be causing the ion-item click to malfunction in Ionic 4 on iOS devices?

ion-item clickable event is not working on iOS but it works fine on Android. I have been searching for a solution and have wasted a lot of time on it. Can someone please help me with this issue? <ion-content> <div> <ion-sear ...

What are the best methods for protecting a soda?

My code is in strict mode, and I am encountering an issue with the following snippet: const a: string[] = []; // logic to populate `a` while (a.length > 0) { const i: string = a.pop(); // This line is causing an error console.log(i); // additio ...

The latest version of npm packages is not displayed when you hover over them in Visual Studio Code

Previously in package.json, I was able to check the latest versions of packages by hovering over each package version as a "tooltip", but that feature seems to have disappeared now. I am using VSC version 1.19.2. I am navigating through a proxy. I ha ...