Home > database >  How do I hide an Agular component on all routes that correspond to a certain pattern?
How do I hide an Agular component on all routes that correspond to a certain pattern?

Time:05-19

I am working on an e-commerce app who's front-end is made in Angular 13.

The UI has a sidebar which I do not want to display on the product details page.

For this purpose, in app\app.component.ts I have:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'E-commerce';
  constructor(private router: Router) {}

  ngOnInit() {}

  /**
   * Check if the router url contains the specified route
   *
   * @param {string} route
   * @returns
   * @memberof AppComponent
   */
   hasRoute(route: string) {
    return this.router.url.includes(route);
  }
}

In app\app.component.html:

<div >
  <app-navbar></app-navbar>
    <div >
      <div >
        <div *ngIf="!hasRoute('products/show/:id')" >
          <app-sidebar ></app-sidebar>
        </div> 
        
        <div >
          <router-outlet></router-outlet>
        </div>
      </div>
    </div>
  <app-footer ></app-footer>
</div>

Stackblitz

See a "live demo" HERE.

The problem

For a reason I have been unable to understand, this solution fails, and the sidebar is displayed anywhere on the app.

What am I doing wrong?

CodePudding user response:

<div *ngIf="notProductDetails()" >
   <app-sidebar ></app-sidebar>
</div> 

HTML ^^^

constructor() {}
public notProductDetails(): void {
    return !window.location.pathname.startsWith('/products/show/');
}

TS

Simply use the window location to pull the pathname instead of injecting the router - remove the constructor injection. Also no need to pass in a prop value there, because you only have a single string you are asserting.

CodePudding user response:

In that way, you are running that value just one time. In order to achieve this you can subscribe to the router events like this:

public showBar: boolean = true;

constructor(private readonly router: Router) {
   this.router.events
      .pipe(filter((event) => event instanceof NavigationEnd))
      .subscribe(({ urlAfterRedirects }: NavigationEnd) =>
        this.showBar = this.hasRoute(urlAfterRedirects)
      );
}
<div *ngIf="showBar" >
   <app-sidebar ></app-sidebar>
</div> 

In this way, you are updating the showBar value every time the navigation end.

  • Related