角度2:根据路径更改视图的静态部分

时间:2016-06-21 09:44:10

标签: javascript typescript angular routing angular2-changedetection

首先,抱歉这个奇怪的标题。我无法找到更好的摘要。

所以我想要的是创建一个由基本的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>

&#34; mainApp.component.ts&#34;看起来像这样:

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/loginlocalhost:4200/home,因为它呈现mainApp.component,检查哪个是当前路由并相应地显示标题时,这很正常。但是,当我通过例如改变路线时点击按钮

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

navigateToHome()只是

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

标题保持不变,因为更改检测不会将路径更改纳入concideration,因此不会重新运行[ngSwitch] /重新呈现mainApp.component。

我已经考虑将标题包含在它们所属的组件模板中,但是如果有一种方法可以在主组件中进行,我宁愿这样做。

如果你们知道如何解决这个问题,或者更好/更好的方式/最佳实践方式,我很高兴听到它。

感谢。

1 个答案:

答案 0 :(得分:0)

这里的答案是订阅像这样的路由器事件:

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

这通常会订阅路由器事件,并且只要导航通过检查返回值的url属性成功结束,就会更改currentLocation变量。

我在(在这篇文章发布时)当前的路由器版本@ angular / routerv3.0.0-alpha8实现了这个工作正常。