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

如何在Bootstrap模态框中传递用户ID并展示对应数据(Angular场景)

实现Angular循环项点击后在Bootstrap模态框展示用户数据

1. 组件类中定义选中用户变量

在你的组件 .ts 文件里,先声明一个变量存储点击选中的用户数据:

selectedUser: any; // 可根据实际数据结构定义更具体的类型,比如 interface

2. 修改按钮逻辑,传递当前用户数据

替换原按钮代码,移除原生Bootstrap的data-toggle/data-target,改用Angular点击事件传递当前循环项的用户数据,并手动控制模态框显示:

<button type="button" class="btn btn-primary mb-2" (click)="openModal(meals)">W / D</button>

然后在组件类中实现openModal方法:

openModal(user: any) {
  this.selectedUser = user;
  // 手动触发Bootstrap模态框
  const modalEl = document.getElementById('exampleModal');
  if (modalEl) {
    const modal = new (window as any).bootstrap.Modal(modalEl);
    modal.show();
  }
}

注意:确保项目已引入Bootstrap JS文件,否则无法调用bootstrap.Modal

3. 模态框绑定选中用户的数据

修改模态框HTML,通过selectedUser展示对应信息:

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">{{selectedUser?.name}} 详情</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p>用户ID:{{selectedUser?.client_id}}</p>
        <p>已存款:{{selectedUser?.deposited}}</p>
        <p>已支付:{{selectedUser?.paids}}</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary" (click)="sattle(selectedUser.client_id, selectedUser.deposited, selectedUser.paids)">结算</button>
      </div>
    </div>
  </div>
</div>

使用?.可选链操作符是为了避免selectedUser未赋值时触发报错。

4. 清理原代码的问题点

  • 移除循环项按钮上重复的id="id",循环渲染的元素不能使用相同ID,会导致DOM冲突
  • 将按钮类型从submit改为button,避免意外触发表单提交

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:41:04