1

まず、奇妙なタイトルには申し訳ありません。私はより良い要約を見つけることができませんでした。アングル2:パスに応じてビューの静的部分を変更する

私が望むのは、基本的な3パート構造(ヘッダー/コンテンツ/フッター)で構成されるアプリケーションを作成することです。アクティブなルートに応じて、ヘッダー部分が変更されます(すべてのヘッダーは独自のコンポーネントです)。

これまで「mainApp.component」で[ngSwitch]文によって決定され表示され、次のようになりますされ、ヘッダー:「mainApp.component.ts」はこのようになります

<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、チェックをレンダリングするように私は手動で私のlocalhost:4200/loginまたはlocalhost:4200/homeに行くとき

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() { 

    } 
} 

これだけで正常に動作します。しかし、私が経路を例えばnavigateToHome()が変化検出conciderationに経路変更を取るていないため、再実行しないようにヘッダは同じまま単に

navigateToHome() { 
    this.router.navigate(['/home']); 
} 

ある

<span class="btn btn-default headerButton homeButton" (click)="navigateToHome()"></span> 

介してボタンクリック[ngSwitch]/mainApp.componentを再レンダリングします。

私は既に彼らが属しているコンポーネントテンプレートの中にヘッダーを含めることを考えましたが、主なコンポーネントでそれを行う方法があればそれを好むでしょう。

もしあなたがこれを解決する方法、あるいはそれをより良く/別の方法/最良の方法で行う方法を知っていたら、それを聞いてうれしいです。

ありがとうございました。

答えて

0
ここでの答えはそうのようなルータのイベントをサブスクライブすることです

this.router.events.subscribe((e) => {e instanceof NavigationEnd? this.currentLocation = '/' + e.url.split('/')[1] : ''}); 

これは一般的なルータのイベントにサブスクライブし、ナビゲーションが返されるのurlプロパティをチェックすることにより、正常に終了したときにcurrentLocation変数を変更します値。

私はこれを実装しました(この記事の時点で)現在のルータバージョン@ angular/routerv3.0.0-alpha8はうまく動作します。

関連する問題