Search code examples
javascriptangularangular-ui-routerangular7-router

Angular how to hide a global component when a specific route is opened?


I'm not sure whether this is possible or not in angular but I wanted to hide a global component when a specific route is opened.

Say for example I have the following:

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]

With this, its a given that when I want to view the StudentList Component, then the url by default becomes localhost4200:/StudentList and the same with SchoolMotto it becomes localhost4200:/SchoolMotto.

Within the StudentListComponent, is an ag-grid that displays list of students, and when you click one of those students the url becomes something like this: localhost4200:/StudentList/view/cf077d79-a62d-46e6-bd94-14e733a5939d and its another sub-component of SchoolList that displays the details of that particular student.

I wanted to hide the Global banner component when the url has something like that: localhost4200:/StudentList/view/cf077d79-a62d-46e6-bd94-14e733a5939d. Only when the user views the specific details of a student.

Something like this:

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 doable or not? If it is, how?


Solution

  • You could use event emitter or subject to emit an event when you're in StudentList/view and use ngIf to hide the banner.

    In your StudentList component.ts :

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

    subscribe to this in your parent component and you can easily hide the banner.