Smokey Dawson
Smokey Dawson

Reputation: 9230

Toggle Component depending on route Angular 4

Hey there Im trying to toggle a component on and off, but I cant seem to get it to work...

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app';
  router: string;

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

app.component.html

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

route configuration

export const ROUTES: Routes = [
  { path: '', component: HomeComponent, pathMatch="full" },
  { path: 'who-we-are', component: WhoWeAreComponent},
  { path: 'our-technology', component: OurTechnologyComponent},
  { path: 'our-work', component: OurWorkComponent },
  { path: 'get-in-touch', component: GetInTouchComponent }
];

index.html

 <base href="/">

so basically If I start at home I want the app-header-home component shown but then as soon as I navigate to a new section I want app-header-home to hide but then If I go back to home I want it to show up again

Thanks

Upvotes: 2

Views: 2796

Answers (2)

Z. Bagley
Z. Bagley

Reputation: 9260

You want to subscribe to route changes, and the change a boolean flag depending on route in your typescript:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  routeHidden = true;

  constructor(
    private router: Router) { }

  ngOnInit() {
    this.router.events.subscribe( (e) => {
      if (e instanceof NavigationStart) {
        if (e.url === "/") {
            this.routeHidden = false;
        } else {
            this.routeHidden = true;
        }
      }
    })
  }

}

and in your html template:

<app-header-home *ngIf="routeHidden"></app-header-home>

Upvotes: 4

Ofek Amram
Ofek Amram

Reputation: 452

Try using the ActivatedRoute service

constructor(private route: ActivatedRoute){
   this.router= route.snapshot.url.join('');
}

Upvotes: 0

Related Questions