首先,對於奇怪的標題感到抱歉。我找不到更好的總結。角度2:根據路徑更改視圖的靜態部分
所以我想要的是創建一個由基本的3部分結構(頭/內容/頁腳)組成的應用程序。根據激活的路線,標題部分應該改變(每個標題本身就是一個組件)。
到目前爲止所顯示的是在「mainApp.component」的[ngSwitch]聲明確定的,看起來像這樣的標題:
<span [ngSwitch]="currentLocation">
<span *ngSwitchWhen="'/login'"><login-header></login-header></span>
<span *ngSwitchWhen="'/home'"><home-header></home-header></span>
</span>
<div class="content"><router-outlet></router-outlet></div>
<app-footer></app-footer>
凡「mainApp.component.ts」看起來是這樣的:
import { Component, OnInit } from '@angular/core';
import {ROUTER_DIRECTIVES} from '@angular/router';
import {HomeHeaderComponent} from './home-header';
import {LoginHeaderComponent} from './login-header';
import {FooterComponent} from './footer';
import {Router} from '@angular/router';
@Component({
moduleId: module.id,
selector: 'app',
templateUrl: 'mainApp.component.html',
styleUrls: ['mainApp.component.css'],
directives: [HomeHeaderComponent, LoginHeaderComponent, FooterComponent, ROUTER_DIRECTIVES],
providers: []
})
export class mainApp implements OnInit {
public currentLocation: string;
constructor(public router: Router) {
this.currentLocation = location.pathname;
}
ngOnInit() {
}
}
當我去我的localhost:4200/login
或localhost:4200/home
手動,因爲它呈現mainApp.component,檢查這是當前的路徑,並相應地顯示頁眉這一切正常。但是,當我通過例如經由
<span class="btn btn-default headerButton homeButton" (click)="navigateToHome()"></span>
按鈕點擊凡navigateToHome()僅僅是
navigateToHome() {
this.router.navigate(['/home']);
}
頭保持不變作爲變化檢測不走路徑改變成concideration,因此不重新運行[ngSwitch] /重新顯示mainApp.component。
我已經想過將組件模板包含在它們所屬的組件模板中,但是如果有一種方法可以在主組件中執行它,我更願意使用它。
如果你們對如何解決這個問題有所瞭解,或者有更好的方法/以另一種方式/最佳實踐的方式,我很樂意聽到它。
謝謝。