Skip to content Skip to sidebar Skip to footer

Hide And Show Angular 4 Component Depending On Route

Hi there Im not sure if this is possible... basically I want to be able to show a component but only if the route matches and hide a component if the route matches Ive tried this a

Solution 1:

check the router.url in the template:

<app-header><app-header><app-header-home *ngIf="router != '/ur_route'"></app-header-home> //component I want hidden unless url /home
<router-outlet></router-outlet><app-footer></app-footer>

in app.component.ts inject the router.

exportclassAppComponent {
  title = 'app';
  router: string;

  constructor(private _router: Router){

          this.router = _router.url; 
    }
}

Solution 2:

The accepted answer didn't work, because i think the variable will be assigned only once, then when we navigate, that variable will not be updated (component already initialized).

here's how I did it.. We inject the router in the component we want to hide :

constructor(private _router: Router){}

then in our template :

<div *ngIf="_router.url != '/login'">
  ... your component html ...
</div>

Solution 3:

This is in reference to the comment posted by SUNIL JADHAV. Instead of exposing the router handle on the templates we can define it inside a function and call it in the template.

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

@Component({
  selector: 'my-component',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss']
})
exportclassMyComponent implements OnInit {

  constructor(
    private router: Router,
  ) {}

  ngOnInit() {
  }


  /**
   * Check if the router url contains the specified route
   *
   * @param {string} route
   * @returns
   * @memberofMyComponent
   */hasRoute(route: string) {
    returnthis.router.url.includes(route);
  }
}

Then in the html file we can use it like so

<!-- First view --><div *ngIf="hasRoute('home')">
    First View
</div><!-- Second view activated when the route doesn't contain the home route --><div *ngIf="!hasRoute('home')">
    Second View
</div>

Solution 4:

Below code worked for me.

I am hiding side navigation in login screen.

 <div *ngIf="!router.url.includes('login')"class="sidenav">

Solution 5:

Take a look at this Angular Rounting guide.

You'll need a method called canActivate, this mehtod return a boolean and its in a service.

This I what works form me:

{path :'getIn', component:GetinComponent , canActivate: [GetInService] }

Post a Comment for "Hide And Show Angular 4 Component Depending On Route"