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

Error message "process.nextTick(() => { throw err; });" encountered while attempting to build an Angular image in a Docker environment

Looking at my Dockerfile below, I had everything set up just fine two weeks ago when I ran docker build -t imgTest .. However, today when I tried running it again, I encountered the following error: Node.js version v21.0.0 detected. Odd numbered Node.js ve ...

Transferring a variable from an Angular 2 constructor into the template via the then statement

I'm struggling with implementing a secure login system. My goal is to first check the device's native storage for an item named 'user', then verify if the user exists in our database, and finally retrieve the unique id associated with t ...

Guide on extracting just the key and its value from a Filter expression in a DynamoDB Query using Typescript

Presented here is a filter expression and Key Condition. The specific set of conditions are as follows: {"Age":{"eq":3},"Sex":{"eq":"MALE"}} const params: QueryCommandInput = { TableName: my_tab ...

Issues with ng2-pdf-viewer arising in Angular versions 12 and above

Issue Detected If 'pdf-viewer' is an Angular component with the 'src' input, ensure it is included in this module. If 'pdf-viewer' is a Web Component, add 'CUSTOM_ELEMENTS_SCHEMA' to '@NgModule.schemas' of ...

Issue: The JSX element 'X' is missing any constructors or call signatures

While working on rendering data using a context provider, I encountered an error message stating "JSX Element type Context does not have any constructor or call signatures." This is the code in my App.tsx file import { Context } from './interfaces/c ...

When the appdir is utilized, the subsequent export process encounters a failure with the error message "PageNotFoundError: Module for page /(...) not

I have implemented NextJS with the experimental appDir flag and organized my pages in the following manner: https://i.stack.imgur.com/M7r0k.png My layout.tsx file at the root and onboard look like this: export default function DefaultLayout({ children }) ...

Does the Angular library "ngx-paypal" have the capability to process recurring payments?

For my Angular project, I am interested in utilizing the paypal library ngx-paypal. While I have experience with integrating javascript libraries, I specifically want to incorporate an Angular library such as https://www.npmjs.com/package/ngx-paypal Does ...

Initial values are not retained for nested form components upon submission

In an attempt to incorporate nested form components in Angular using reactive forms and ControlValueAccessors, I have been following a helpful guide available at the following link: While most of my implementation is working correctly, I am encountering o ...

Setting the date of the NgbDatePicker through code

I have implemented two NgbDatePicker components in my project: input( type="text", ngbDatepicker, #d="ngbDatepicker", [readonly]="true", formControlName='startDate', (dateSelect)='setNew ...

Dealing with Incoming HTML Content from Backend in Angular 5

My backend is sending me HTML with a Facebook login, but the observable is attempting to parse it before I can make any changes... I'm having trouble explaining this issue to search engines, so any help understanding the professional terms related to ...

Is it necessary to include @types/ before each dependency in react native?

I am interested in converting my current react native application to use typescript. The instructions mention uninstalling existing dependencies and adding new ones, like so: yarn add --dev @types/jest @types/react @types/react-native @types/react-test- ...

Issue: Unable to locate control with the specified name

Having trouble submitting a reactive form with form arrays, I've searched through various solutions on different forums without success. It seems like I may be overlooking something obvious. The errors I'm encountering are "ERROR Error: Cannot fi ...

"Continue to shine until the rendering function displays its source code

I've encountered a strange issue where I'm using lit until to wait for a promise to return the template, but instead of the desired output, the until's function code is being rendered. For example: render() { return html` <div c ...

Challenge with module declaration in index.d.ts during upgrade from Angular 8 to 9 (excluding Material)

In my index.d.ts file, I have declared two modules like so: declare module 'googlemaps'; declare module 'detect-resize'; Previously, these declarations worked perfectly fine, allowing me to utilize these modules. The googlemaps module ...

Instructions for incorporating a TypeScript type into a Prisma model

I am trying to incorporate a Type Board into one of my Prisma models. However, I am encountering an error stating that "Type 'Board' is neither a built-in type, nor refers to another model, custom type, or enum." Can someone provide guidance on h ...

Is it possible to use AngularJS promise scheduling with `async`/`await` syntax?

When working with AngularJS services, TypeScript often recommends that I switch my code to use async/await functions. While I understand that using the await keyword is compatible with third-party promises because it essentially translates to calling then ...

Unforeseen results arise when using the ng-if directive on a DIV element within an Angular context

@angular/upgrade/static Attempting to upgrade an AngularJS controller to Angular context using UpgradeModule from '@angular/upgrade/static' Encountering issues when changing ng-show to ng-if on span or div elements, as the enclosed content does ...

Can TypeScript ascertain the object's type dynamically based on the key of its proxy name?

I am creating a wrapper class that will handle various operations related to the user entity. These operations include checking if the user is a guest, verifying their permissions, and more. One of the functions I want to implement in this class is an acce ...

Issues encountered when setting up a Context Provider in React using TypeScript

I am currently in the process of setting up a Cart context in my React TypeScript project, inspired by the implementation found here: https://github.com/AlexSegen/react-shopping-cart/blob/master/src/contexts/CartContext.js. I'm encountering some conf ...

Retrieve JSON data from a 404 response using the Http.get() method

I am attempting to retrieve JSON from a 404 response, but I am only receiving the Response {_body: "{myJSON}", status: 404, ok: false, statusText: "Not Found", headers: Headers…} How can I access the object itself so that I can display it in my HTML u ...