How can Angular hide a global component when a particular route is accessed?

Is it possible to hide a global component in Angular when a specific route is opened?

For instance, consider the following code:

app.component.html

<app-header></app-header>

<app-banner></app-banner> <!-- Global Component I want to hide -->

<div class="body-container">
    <router-outlet></router-outlet>
</div>

<app-footer></app-footer>

app-routing.module.ts

import {NgModule} from '@angular/core';
import {Route, RouterModule} from '@angular/router';
import { StudentListComponent } from './Components/StudentList/StudentList.component';
import { SchoolMottoComponent } from './Components/SchoolMotto/SchoolMotto.component';

const routes: Routes = [
    {path: 'StudentList', component: StudentListComponent },
    {path: 'SchoolMotto', component: SchoolMottoComponent }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})

export class AppRoutingModule { }
export const routingComponents = [StudentListComponent, SchoolMottoComponent]

In this scenario, when viewing the StudentList Component, the URL defaults to localhost4200:/StudentList and similarly for SchoolMotto it becomes localhost4200:/SchoolMotto.

When a student is clicked within the StudentListComponent, the URL changes to something like this: localhost4200:/StudentList/view/cf077d79-a62d-46e6-bd94-14e733a5939d showing details of that student.

The requirement is to hide the global banner component only when the URL includes localhost4200:/StudentList/view/cf077d79-a62d-46e6-bd94-14e733a5939d. Is there a way to achieve this?

Proposed solution:

app.component.html

<app-header></app-header>

**<app-banner *ngIf="router != '/StudentList/view/'"></app-banner> <!-- Global Component I want to hide -->**

<div class="body-container">
    <router-outlet></router-outlet>
</div>

<app-footer></app-footer>

Is this achievable? If so, how can it be implemented?

Answer №1

If you find yourself in the StudentList/view scenario, consider utilizing event emitter or subject to trigger an event that will allow you to hide the banner using ngIf.

Within your StudentList component.ts file:

export class StudentList {
    bannerSubject: Subject<any> = new Subject<any>();
    
    ngOnInit() {
         bannerSubject.next(true);
    }
}

By subscribing to this in your parent component, you can easily control the visibility of the banner.

Answer №2

Utilize component interaction and a service to achieve this goal

Implement Rxjs Observables for help in the process

Emit an event once you reach the student view component, then receive and handle that event in the app component to change the view condition

Create a New Service:

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs';

@Injectable()
export class RouteService {

  private routeChangedSource = new Subject<string>();

  // Observable string streams
  routeChanged$ = this.routeChangedSource.asObservable();

  // Service message commands
  changeRoute(mission: string) {
    this.routeChangedSource.next(mission);
  }
}

Student View Component.

import { Component }          from '@angular/core';

import { routeService }     from './mission.service';

@Component({
})
export class MissionControlComponent implements ngOnInit{
  constructor(private routeService: routeService) {}

  ngOnInit() {
    this.routeService.changeRoute(mission);
  }
}

App Component:

import { Component, Input, OnDestroy } from '@angular/core';

import { RouteService } from './route.service';
import { Subscription }   from 'rxjs';


export class AppComponent implements OnDestroy {
  studentView = false;
  constructor(private routeService: RouteService) {
    this.subscription = routeService.routeChanged$.subscribe(
      value => {
        this.studentView = true;
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

Update your App Component as follows:

<app-header></app-header>

<app-banner *ngIf="!studentView"></app-banner>

<div class="body-container">
    <router-outlet></router-outlet>
</div>

<app-footer></app-footer>

Answer №3

<app-header></app-header>

<app-banner *ngIf="myService.hideGlobalComp"></app-banner> <!-- This is the Global Component that will be hidden when condition is met -->

<div class="body-container">
    <router-outlet></router-outlet>
</div>

<app-footer></app-footer>

in the ts file:

onCellClicked($event) { // Add this code to where you need it in your method 

    this.route.parent.url.subscribe(urlPath => {
      this.url = urlPath[urlPath.length - 1].path;
    });

   if(this.url === 'StudentList/view') {
  this.myService.hideGlobalComp = true;
}

}

}

Answer №4

To implement this in your TypeScript file, follow these steps:

  1. Create a new variable called router: string;
  2. In the constructor, add the following code snippet:

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

Then, use the same code in your HTML file. If you encounter any issues, feel free to reach out for assistance.

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

Updating a connected model in Sequelize using another model

Seeking guidance on updating a model with new associations in Sequelize. The model involves a many-to-many relationship with a join table. Attempted this code snippet: app.patch('/api/team/:id/newplayers', function(request, response){ const pl ...

Modules failing to load in the System JS framework

Encountering a puzzling issue with System JS while experimenting with Angular 2. Initially, everything runs smoothly, but at random times, System JS struggles to locate modules... An error message pops up: GET http://localhost:9000/angular2/platform/bro ...

Angular 10 experiences issues with JWT Helper service causing errors

Currently, I'm facing an issue with my Angular 10 project and the latest JWT Helper service. Unfortunately, the app is failing to compile. The error message that pops up reads as follows: ERROR in node_modules/@auth0/angular-jwt/lib/jwthelper.servic ...

Exploring the new features of utilizing buttons with the onClick method in the updated nextJS version 14.1.3

"implement customer" import React, { useState } from "react"; import { FaChevronLeft, FaChevronRight } from "react-icons/fa"; export default function HeroSlider() { const images = [ "/images/homepage/home-1.jpeg&qu ...

Discovering the parameter unions in Typescript has revolutionized the way

My current interface features overloaded functions in a specific format: export interface IEvents { method(): boolean; on(name: 'eventName1', listener: (obj: SomeType) => void): void; on(name: 'eventName2', listener: (obj: Som ...

Navigating with Node.js and angular

I'm struggling with redirecting POST requests using Node.js, Express, and Angular. Typically, we'd use forms like this: index.ejs <!DOCTYPE html> <html> <head> <title>Redirect Example</title> </head> <bo ...

When scrolling, dynamically change the background color by adding a class

I am looking to achieve a scroll effect where the color of the menu buttons changes. Perhaps by adding a class when scrolling and hitting the element? Each menu button and corresponding div has a unique ID. Can anyone suggest what JavaScript code I should ...

Setting up grunt-contrib-nodeunit to generate JUnit XML output: a step-by-step guide

I have been searching for information on how to configure reporters in the grunt-contrib-nodeunit module, as I recently added this task to my Gruntfile.js. nodeunit: { all: ['nodeunit/**/*.test.js'], } Does anyone know how to instruct Grunt ...

Only line breaks are permitted in Mustache.js, all other HTML characters are escaped

After a user submits input, I am generating comments and displaying them using Mustache.js. When it comes to rendering the comments, I have found that replacing user-entered line breaks (\n) with <br/> allows them to display as HTML breaks. To ...

Storing intricate items in a JavaScript database can be tricky. Using JSON.stringify() can sometimes lead to unexpected errors

In my project, I have a class called Player and a list of players named gameData. My goal is to save and retrieve this gameData from a database so that user information remains intact even after the bot restarts or crashes. However, when attempting to use ...

I am looking to showcase images beside individuals' names or photos on my website in a vertical arrangement, similar to how it is done on Facebook

Looking for suggestions on how to display images uploaded by users on my webpage in a way similar to Facebook, with the user's photo displayed beside each image. Any recommendations or website links would be greatly appreciated. Thanks, Santosh Sahu ...

I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys. private parentArray: {}[] = [ { Id: 1, Name: &ap ...

The browser is struggling to interpret the incorrect HTML content

I am looking for a way to create a function that can retrieve account data from my database and organize it in a user-friendly HTML table where users can make selections and modifications. The code I have so far is as follows: $.ajax({ url: "./dat ...

Removing an element in Vue.js

Can someone help me with a Vue.js issue I'm having? I'm working on a quiz and I want to add a button that deletes a question when clicked. Here's what I've tried so far: deleteQuestion(index) { this.questions.splice(index, ...

Ways to determine if a website is being accessed from a mobile device or a computer without relying on TeraWurfl technology

After my search on the internet yielded no answers, I decided to post my question here. Is there a method available to detect whether a site is being accessed from a computer or mobile device without using TeraWurfl? I'm looking for a simple code snip ...

The issue with HTML where the header and footer elements are continuously repeating when

I'm struggling with the title header and footer repeating on every printed page. I just want to show the title at the top of the page and display the footer at the end of the print page. Can anyone provide a solution or suggestion? You can view my fid ...

Using an aria-label attribute on an <option> tag within a dropdown menu may result in a DAP violation

Currently, I am conducting accessibility testing for an Angular project at my workplace. Our team relies on the JAWS screen reader and a helpful plugin that detects UI issues and highlights them as violations. Unfortunately, I've come across an issue ...

What is the integration between redux and next.js like?

I am currently trying to integrate Redux into an existing Next.js project, but I am struggling to grasp how the store functions server-side. I came across this example that I am following: https://github.com/vercel/next.js/blob/canary/examples/with-redux ...

Regularly updating a book's interactive pages with turn.js technology

I experimented with generating dynamic content in turn.js using the sample provided here. This is an excerpt of the code I have written: <body> <div id="paper"> </div> </body> <script type="text/javascript"> $(win ...

Issue with CasperJS: The function this.waitForUrl is not defined and is causing an error

My casperJS script handles form filling, however I encountered the following error message: A TypeError occurred: 'undefined' is not a function (evaluating 'this.waitForUrl') I suspect this might be an issue with using an outdated ver ...