即使在远离它的情况下也能保持家庭组件

时间:2017-05-11 11:08:41

标签: angular angular2-routing

有没有办法坚持应用程序的主要'家庭'组件,即使我导航到另一个组件?例如,在我的应用中,我的主页指向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>

SingleTeam:

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;
    })
  }
}

SingleTeam 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>

1 个答案:

答案 0 :(得分:0)

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

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

或将其移至指定的商店。

检查Plunker !!

希望这会有所帮助!!