You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中点击链接/按钮如何在同页面侧边显示视图?

Angular实现页面内侧边加载视图方案

1. 调整父组件布局

先在承载列表和视图的父组件(比如DashboardComponent)里,用flex布局拆分左右区域:

父组件模板(dashboard.component.html):

<div class="page-container">
  <!-- 左侧列表组件 -->
  <app-item-list></app-item-list>
  <!-- 右侧路由出口,用来渲染目标视图 -->
  <div class="view-area">
    <router-outlet></router-outlet>
  </div>
</div>

对应的CSS样式:

.page-container {
  display: flex;
  gap: 1.5rem;
  padding: 1rem;
}
app-item-list {
  width: 320px;
  border-right: 1px solid #e5e7eb;
  padding-right: 1.5rem;
}
.view-area {
  flex: 1;
  min-width: 0; /* 防止内容溢出时布局错乱 */
}

2. 配置子路由

在路由配置文件(app-routing.module.ts)里,给父路由添加子路由,让目标视图组件渲染在右侧的路由出口中:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { ItemDetailComponent } from './item-detail/item-detail.component';

const routes: Routes = [
  {
    path: 'dashboard',
    component: DashboardComponent, // 父组件,包含列表和路由出口
    children: [
      { path: 'item/:id', component: ItemDetailComponent }, // 点击后加载的详情组件
      { path: '', redirectTo: 'item/1', pathMatch: 'full' } // 默认加载第一个详情
    ]
  },
  // 其他路由配置...
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

3. 列表组件设置跳转链接

在列表组件(item-list.component.html)里,用routerLink指令指向子路由,避免页面跳转:

<ul class="item-list">
  <li *ngFor="let item of itemList">
    <a [routerLink]="['/dashboard/item', item.id]">{{ item.title }}</a>
  </li>
</ul>

点击这些链接时,Angular会更新路由,同时在父组件右侧的router-outlet中加载对应的ItemDetailComponent,全程不会刷新页面或打开新标签页。

可选:用辅助路由实现不改变主路由的侧边加载

如果不需要修改主路由路径,只想在侧边加载视图,可以用命名路由出口:

  1. 父组件模板添加命名路由出口:
<div class="page-container">
  <app-item-list></app-item-list>
  <div class="view-area">
    <router-outlet></router-outlet> <!-- 主路由出口 -->
    <router-outlet name="sidebar"></router-outlet> <!-- 命名侧边出口 -->
  </div>
</div>
  1. 路由配置添加辅助路由:
{
  path: 'item/:id',
  component: ItemDetailComponent,
  outlet: 'sidebar'
}
  1. 列表链接改为指向辅助路由:
<a [routerLink]="[{ outlets: { sidebar: ['item', item.id] } }]">{{ item.title }}</a>

内容的提问来源于stack exchange,提问作者abhinav-sol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 17:52:26