Angular路由问题:跳转子页面时首页内容重复显示
问题原因
Angular 路由的渲染规则是:路由匹配到的组件内容,只会被插入到<router-outlet>标签所在的位置;<router-outlet>标签之外写在模板里的内容属于全局固定内容,访问任何路由都会持续显示。
你当前把首页专属的「全量图片列表+图片详情组件」直接写在了根组件app.component.html的<router-outlet>下方,同时没有给首页单独配置路由组件,导致不管跳转到水果分类页、狗狗分类页,根组件里写死的首页内容都会一直显示在路由出口渲染的分类内容下方,出现重复展示的问题。

修复方案
- 新建独立的首页组件,把原来写在根组件里的全量图片加载、悬停选中、列表渲染、详情组件调用的逻辑全部迁移到首页组件中
- 在路由配置中新增空路径(
'')的默认首页路由,指向新建的首页组件 - 清理根组件模板,只保留全局公共的标题、导航栏和
<router-outlet>标签,删除首页专属的列表、详情组件代码;根组件类中对应的图片加载、悬停处理逻辑也同步删除
修正后的核心代码
1. 路由配置(app-routing.module.ts)
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { FruitFotosComponent } from './fruit-fotos/fruit-fotos.component'; import { HondenFotosComponent } from './honden-fotos/honden-fotos.component'; // 引入新建的首页组件 import { HomeComponent } from './home/home.component'; const routes: Routes = [ // 新增默认首页路由,pathMatch:full 保证空路径完全匹配时才加载首页 {path: '', component: HomeComponent, pathMatch: 'full'}, {path: "fruitfotos", component: FruitFotosComponent}, {path: "hondenfotos", component: HondenFotosComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
2. 根组件模板(app.component.html)
<title>{{title}}</title> <h1>{{title}}</h1> <nav> <a routerLink="/">所有图片</a> <a routerLink="/fruitfotos">Foto's fruit</a> <a routerLink="/hondenfotos">Foto's honden</a> </nav> <!-- 路由出口:所有路由匹配到的页面内容都渲染在此处 --> <router-outlet></router-outlet>
3. 根组件类(app.component.ts)
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = "Yannick's taak"; }
4. 首页组件类(home.component.ts)
import { Component, OnInit } from '@angular/core'; import { Foto } from './model/Foto'; import { FotoService } from './foto.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { fotos!: Foto[]; selectedFoto!:Foto; onHover(foto:Foto): void { this.selectedFoto = foto; } constructor(private fotoService: FotoService){} ngOnInit(): void { this.fotoService.getFotos().subscribe(fotos=>this.fotos=fotos); } }
5. 首页组件模板(home.component.html)
<h1>alle foto's:</h1> <ul> <li *ngFor="let foto of fotos" (mouseover)="onHover(foto)" [style.backgroundColor]="foto.id%2===0?'red':'green'">{{foto.name}}</li> </ul> <app-foto-details [foto]="selectedFoto"></app-foto-details>
水果分类、狗狗分类的组件和服务代码不需要修改,调整完成后访问不同路由时,路由出口会替换渲染对应页面的内容,不会再出现全量列表重复显示的问题。
内容的提问来源于stack exchange,提问作者Yannick Mussche
相关产品推荐
相关产品推荐

