Hide and Show angular 4 component depending on route
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
.
export class AppComponent {
title = 'app';
router: string;
constructor(private _router: Router){
this.router = _router.url;
}
}
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']
})
export class MyComponent implements OnInit {
constructor(
private router: Router,
) {}
ngOnInit() {
}
/**
* Check if the router url contains the specified route
*
* @param {string} route
* @returns
* @memberof MyComponent
*/
hasRoute(route: string) {
return this.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>