【问题标题】:angular 2: Changing static parts of the view according to path角度2:根据路径更改视图的静态部分
【发布时间】:2016-06-21 09:44:09
【问题描述】:

首先,很抱歉这个奇怪的标题。我找不到更好的总结。

所以我想要创建一个包含基本 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/loginlocalhost:4200/home 时,这工作得很好,因为它呈现 mainApp.component,检查哪个是当前路由并相应地显示标题。但是,当我通过例如更改路线时通过按钮单击

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

navigateToHome() 是简单的

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

标头保持不变,因为更改检测不会考虑路由更改,因此不会重新运行 [ngSwitch] / 重新渲染 mainApp.component。

我已经考虑在它们所属的组件模板中包含标题,但如果有办法在主组件中执行此操作,我会更喜欢。

如果你们对如何解决这个问题有任何想法,或者有什么方法可以做得更好/另一种方式/最佳实践的方式,我很高兴听到它。

谢谢。

【问题讨论】:

    标签: javascript typescript angular routing angular2-changedetection


    【解决方案1】:

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

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

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

    我在(在本文发布时)当前路由器版本@angular/routerv3.0.0-alpha8 中实现了这一点,效果很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-27
      • 2017-06-03
      • 2013-05-23
      • 2017-01-25
      • 1970-01-01
      相关资源
      最近更新 更多