You need to enable JavaScript to run this app. Angular项目中基于JSON数据动态加载Bootstrap 4 accordion组件咨询
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目中基于JSON数据动态加载Bootstrap 4 accordion组件咨询

完全可以基于你现有的数据结构完成开发,无需调整JSON格式,按以下步骤实现即可:

实现步骤

1. 组件类中定义数据源

你需要在对应Angular组件的.ts文件中定义tanks数组,绑定你提供的JSON数据:

// 对应业务组件的.ts文件
tanks = [
  {
    "id":"KT025",
    "description":"kt025 is large tank with the 3 doors"
  },
  {
    "id":"KT023",
    "description":"kt023 is medium tank with the 2 doors"
  },
  {
    "id":"KT034",
    "description":"kt034 is small tank with the 2 doors"
  }
]

2. 改造HTML模板实现动态渲染

原有静态模板的结构不需要做大改,只需要把重复的手风琴项替换为*ngFor循环即可,注意动态生成唯一的元素ID保证折叠功能正常:

<div id="accordion" class="accordion">
  <div class="card mb-0">
    <ng-container *ngFor="let tank of tanks">
      <div class="card-header collapsed" data-toggle="collapse" [attr.href]="'#collapse' + tank.id">
        <a class="card-title float-none">
          {{ tank.id }}
        </a>
      </div>
      <div [id]="'collapse' + tank.id" class="collapse" data-parent="#accordion">
        {{ tank.description }}
      </div>
    </ng-container>
  </div>
</div>
  • 代码中使用[attr.href]和[id]属性绑定语法,是为了动态生成符合Bootstrap折叠要求的关联属性,用tank自带的id作为唯一标识,不会出现ID冲突问题
  • 原有Bootstrap4的手风琴交互逻辑完全保留,不需要额外引入其他依赖或修改JS逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 22:15:03