【问题标题】:Persisting home component even when navigating away from it即使在导航离开它时也保留 home 组件
【发布时间】:2017-05-11 11:08:40
【问题描述】:

即使在我导航到另一个组件时,有没有办法保留应用程序的主要“主页”组件?例如,在我的应用程序中,我的主页指向SelectTeamComponent,但每次我导航到SingleTeamComponent,我都会丢失SelectTeamComponent。无论我在哪个页面上,我都希望这个组件保持不变。

这是我在app.module 文件中的路由配置

const appRoutes: Routes = [
  { path: '', component: SelectTeamComponent},
  { path: 'team/:id', component: SingleTeamComponent}
]

更新选定的团队:

 onSelectedTeam(team){
    this.router.navigate(['/team', team.name]);
  }

SelectTeamComponent html:

<ul class="nav" *ngFor="let team of oneTeam">
        <li (click)="onSelectedTeam(team)" routerLinkActive="active">
          <a href="javascript:void(0);">
            <img src="{{team.crest}}" style="width:20px; height:20px;">
            {{team.name}}
          </a>
      </li>
    </ul>

单队:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params} from '@angular/router';

@Component({
  selector: 'app-team',
  templateUrl: './team.component.html',
  styleUrls: ['./team.component.css']
})

export class SingleTeamComponent implements OnInit {
  public teamID;

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.params.subscribe((params: Params)=>{
      let name = params['id'];
      this.teamID = id;
    })
  }
}

单队html:

<div class="content">
    <button class="primary btn">View last 5 games</button>
    <button class="primary btn">View all games this season</button> -->
  <app-last-game [nameOfTeam]="teamName"></app-last-game>
  <div class="col-md-6">
     <div id="accordion" role="tablist" aria-multiselectable="false">
        <app-last-five [nameOfTeam]="teamName"></app-last-five>
      </div>
  </div>
  <div class="col-md-6">
    <app-head-to-head [nameOfTeam]="teamName"></app-head-to-head>
  </div>
  <app-all-games [nameOfTeam]="teamName"></app-all-games>
</div>

【问题讨论】:

    标签: angular angular2-routing


    【解决方案1】:

    您可以将SelectTeamComponent 添加为父组件,并将其他组件添加为子组件,

    const appRoutes: Routes = [
      { path: '', 
       component: SelectTeamComponent,
       children : [
        { path: 'team/:id', component: SingleTeamComponent} 
       ]
      }  
    ]
    

    或将其移至指定的插座。

    检查这个Plunker!!

    希望这会有所帮助!

    【讨论】:

    • 好的,但这不能让我导航到SingleTeamComponent
    • 您的导航如何?你的路由器链接是什么样子的?
    • 我正在浏览每个边栏项目上的 click 函数,该函数在我的边栏组件中触发 this.router.navigate(['/team', team.id]);
    • 你能展示一下你的 SelectTeamComponent, html 的样子吗?
    • 更新原帖
    猜你喜欢
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多