gpt4 book ai didi

javascript - Angular 2 : Changing static parts of the view according to path

转载 作者:行者123 更新时间:2023-11-28 05:52:56 25 4
gpt4 key购买 nike

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

所以我想要创建一个由基本的三部分结构(页眉/内容/页脚)组成的应用程序。根据事件的路由, header 部分应该更改(每个 header 都是一个独立的组件)。

到目前为止,显示的标题由“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']);
}

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

我已经考虑过将标题包含在它们所属的组件模板中,但如果有办法在主组件中做到这一点,我会更喜欢这样做。

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

谢谢。

最佳答案

这里的答案是订阅路由器事件,如下所示:

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

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

我在(撰写本文时)当前路由器版本 @angular/routerv3.0.0-alpha8 中实现了此功能,效果很好。

关于javascript - Angular 2 : Changing static parts of the view according to path,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37940909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com