ค้นหาเว็บไซต์

javascript - สลับคอมโพเนนต์ขึ้นอยู่กับเส้นทาง Angular 4


สวัสดี ฉันกำลังพยายามสลับเปิดปิดคอมโพเนนต์ แต่ดูเหมือนว่าฉันจะทำให้มันทำงานไม่ได้...

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>

การกำหนดค่าเส้นทาง

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 }
];

ดัชนี.html

 <base href="/">

ดังนั้นโดยพื้นฐานแล้ว ถ้าฉันเริ่มจากที่บ้าน ฉันต้องการให้คอมโพเนนต์ app-header-home แสดงขึ้น แต่ทันทีที่ฉันไปยังส่วนใหม่ ฉันต้องการให้ app-header-home ซ่อน และถ้าฉันกลับไปที่บ้าน ฉันต้องการให้มันแสดงขึ้นอีกครั้ง

ขอบคุณ

คำตอบ #1

คุณต้องการสมัครสมาชิกกับการเปลี่ยนเส้นทาง และเปลี่ยนค่าตัวแปรบูลีนขึ้นอยู่กับเส้นทางใน 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;
        }
      }
    })
  }

}

และในแม่แบบ HTML ของคุณ:

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

คำตอบ #2

ลองใช้บริการ ActivatedRoute

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