3

I have a header that I want to hide on certain routes

When your on the home there is nothing next to the route so www.mywebsite.com but then when you log in the route will always have app in it so every page from now on will look like this www.mywebsite.com/app/whateverbasically I want to hide my header when the route has app in it

I have tried to do this.. but It doesnt seem to be working

Any help would be appreciated and if you know a better way to do this please let me know!

component.html

<home-header *ngIf="router != '/app'"></home-header>

component.ts

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


export class RootComponent {
     router: string;

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

EDIT

I have tried to do this..

<home-header *ngIf="router.indexOf('app') > -1"></home-header>

and that did not work

I have also tried to do this..

 export class RootComponent {
    router: string;

    constructor(
        private _router: Router
    ) {
        this._router.events.subscribe(() => this.router = this._router.url );
      }
 }
Smokey Dawson
  • 8,827
  • 19
  • 77
  • 152

3 Answers3

12

I was able to find a solution from http://stackoverflow.com/a/41684866/4194436

In your component.ts

import { Router } from '@angular/router'

//...

constructor(
   public router: Router
) 

then in your component.html

<home-header *ngIf="!router.url.includes('app')"></home-header>

So basically if the route url does not include 'app' show the home-header component.

So basically if the route doesn't include app show the home-header

Smokey Dawson
  • 8,827
  • 19
  • 77
  • 152
  • It does not work on IE because includes is not supported. And with indexOf solution I got "Expected the operants to be of similar type or any" error in VS code – Sandwell Feb 13 '19 at 12:41
  • You can use a polyfill https://stackoverflow.com/questions/31221341/ie-does-not-support-includes-method – Smokey Dawson Feb 13 '19 at 21:06
2

You are setting the router variable only one time, you should add a subscription to the variable changes :

constructor(private _router: Router) {
   // this.router = _router.url;
   this._router.events.subscribe(()=> this.router = this._router.url );
}

You can find more about it here.

Don't forget to unsubscribe on component destruction to avoid memory leaks.

ibenjelloun
  • 7,425
  • 2
  • 29
  • 53
1

Try:

*ngIf="router.indexOf('app') > -1"

Hope this helps

iHazCode
  • 622
  • 4
  • 15