Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide and Show angular 4 component depending on route

Tags:

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 app-header-home shows when the route is '/'which is good but app-header doesnt show at all even when the route inst '/' how can I fix this?

app.component.html

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

app.component.ts

import { Component } from '@angular/core'; import { Router } from '@angular/router';  @Component({   selector: 'app-root',   templateUrl: './app.component.html',   styleUrls: ['./app.component.scss'] }) export class AppComponent {   title = 'app';    constructor(     private router: Router   ) {    } } 

Thanks

like image 502
Smokey Dawson Avatar asked Dec 08 '17 03:12

Smokey Dawson


People also ask

What does the * * path in Angular router do?

Setting up wildcard routeslink The Angular router selects this route any time the requested URL doesn't match any router paths. To set up a wildcard route, add the following code to your routes definition. The two asterisks, ** , indicate to Angular that this routes definition is a wildcard route.

How would I restrict access to routes in Angular?

Include AuthGuard to Route Now for each request of the route, the verify() function will be called and if the verify() function returns true, then only we can access the particular route. If it returns false, we are not able to access it. This is how we can restrict the routes from unauthorized user access.

How does Angular routing handle route parameters?

To access the route parameters, we use route.snapshot , which is the ActivatedRouteSnapshot that contains information about the active route at that particular moment in time. The URL that matches the route provides the productId . Angular uses the productId to display the details for each unique product.


1 Answers

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;      } } 
like image 183
Sachila Ranawaka Avatar answered Sep 20 '22 12:09

Sachila Ranawaka