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

Angular路由与数组:基于按钮交互加载指定数组的技术问询

Angular 实现按按钮点击加载对应数组的方案

1. 先统一管理你的数组数据

别把9个数组零散存放,建议用映射对象关联库类型与对应属性数组,后续维护起来超省心,不用写一堆if-else判断。可以把它放在单独的常量文件或服务里:

// src/app/shared/library-data.ts
export const LIBRARY_DATA = {
  test: ['测试属性A', '测试属性B', '测试属性C', '测试属性D', '测试属性E', '测试属性F', '测试属性G', '测试属性H', '测试属性I'],
  design: ['设计属性1', '设计属性2', '设计属性3', '设计属性4', '设计属性5', '设计属性6', '设计属性7', '设计属性8', '设计属性9'],
  // 剩下7个类型依次补充,比如 backend、frontend 等
};

// 定义类型枚举,避免拼写错误
export type LibraryType = keyof typeof LIBRARY_DATA;

2. 第一页:库类型选择组件实现

在第一个页面(比如library-select.component)中,遍历所有库类型生成按钮,点击时跳转到属性页面并携带选中的类型参数:

模板文件 (library-select.component.html)

<div class="library-btn-group">
  <button 
    *ngFor="let type of libraryTypes" 
    (click)="goToProperties(type)"
    class="library-btn"
  >
    {{ getTypeDisplayName(type) }}
  </button>
</div>

组件逻辑 (library-select.component.ts)

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { LIBRARY_DATA, LibraryType } from '../shared/library-data';

@Component({
  selector: 'app-library-select',
  templateUrl: './library-select.component.html',
  styleUrls: ['./library-select.component.css']
})
export class LibrarySelectComponent {
  libraryTypes: LibraryType[] = Object.keys(LIBRARY_DATA) as LibraryType[];

  constructor(private router: Router) {}

  goToProperties(type: LibraryType) {
    // 跳转到属性页面,通过查询参数传递选中的库类型
    this.router.navigate(['/library-properties'], { queryParams: { type } });
  }

  // 给类型添加友好的显示名称,比如 test 显示为「测试领域」
  getTypeDisplayName(type: LibraryType): string {
    const nameMap: Record<LibraryType, string> = {
      test: '测试领域',
      design: '设计领域',
      // 补充剩下7个类型的显示名称
    };
    return nameMap[type] || type;
  }
}

3. 配置路由

在app-routing.module.ts中配置两个页面的路由规则:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LibrarySelectComponent } from './library-select/library-select.component';
import { LibraryPropertiesComponent } from './library-properties/library-properties.component';

const routes: Routes = [
  { path: '', component: LibrarySelectComponent },
  { path: 'library-properties', component: LibraryPropertiesComponent },
];

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

4. 第二页:属性按钮组件实现

在第二个页面(library-properties.component)中,通过ActivatedRoute获取路由参数,从映射对象中取出对应属性数组并渲染按钮:

组件逻辑 (library-properties.component.ts)

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { LIBRARY_DATA, LibraryType } from '../shared/library-data';

@Component({
  selector: 'app-library-properties',
  templateUrl: './library-properties.component.html',
  styleUrls: ['./library-properties.component.css']
})
export class LibraryPropertiesComponent implements OnInit {
  currentProperties: string[] = [];
  currentLibraryName: string = '';

  constructor(
    private route: ActivatedRoute,
    private router: Router
  ) {}

  ngOnInit(): void {
    // 监听路由参数变化,适配用户刷新页面的场景
    this.route.queryParams.subscribe(params => {
      const type = params['type'] as LibraryType;
      if (type && LIBRARY_DATA[type]) {
        this.currentLibraryName = this.getTypeDisplayName(type);
        this.currentProperties = LIBRARY_DATA[type];
      } else {
        // 参数无效时,跳回选择页面或显示提示
        this.router.navigate(['/']);
      }
    });
  }

  getTypeDisplayName(type: LibraryType): string {
    const nameMap: Record<LibraryType, string> = {
      test: '测试领域',
      design: '设计领域',
      // 和第一页保持一致的显示名称
    };
    return nameMap[type] || type;
  }
}

模板文件 (library-properties.component.html)

<div class="properties-container">
  <h2>{{ currentLibraryName }} 属性列表</h2>
  <div class="property-btn-group">
    <button 
      *ngFor="let prop of currentProperties" 
      class="property-btn"
    >
      {{ prop }}
    </button>
  </div>
</div>

5. 后续扩展

剩下的7个数组,你只需要在LIBRARY_DATA对象里继续添加键值对,同时在两个组件的getTypeDisplayName方法中补充对应显示名称即可,核心逻辑完全不用修改,扩展性拉满~

如果后续需要从后端加载属性数据,只需要把LIBRARY_DATA换成服务的请求方法(比如this.libraryService.getProperties(type).subscribe(...)),整体架构无需调整。

内容的提问来源于stack exchange,提问作者pennyBoy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:18:28