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

Angular 4中使用ng-bootstrap模态框无法获取多参数值的问题

解决ng-bootstrap模态框无法接收多参数(Id和Name)的问题

我看到你在使用ng-bootstrap模态框时遇到了只能获取Id、无法获取并展示Name的问题,这主要是因为方法参数定义不匹配和模态框数据传递方式错误导致的,下面是具体的修复方案:

问题根源分析

  1. 你的HTML中onOne(info.Id, info.Name)传递了两个参数,但TS里的onOne方法定义为(content, data),这导致第二个参数(Name)被当成了模态框的配置选项(而非业务数据),自然无法正确获取。
  2. ng-bootstrap的modalService.open()方法第二个参数是模态框的配置项(如尺寸、背景点击关闭等),不是用来传递业务数据的,需要通过模板上下文或组件实例来传递数据。

具体修复步骤

1. 修正HTML中的点击事件传递

推荐直接传递整个info对象(更简洁,避免参数顺序错误):

<ng-container *ngFor="let info of Data"> 
  <div *ngIf="info.State==='1'" > 
    <button [id]="info.Id" class="btn btn-outline-secondary" (click)="onOne(content, info)"> 
      {{info.Name}} 
    </button> 
  </div> 
</ng-container>

2. 调整TS中的onOne方法,正确传递数据到模态框

修改方法参数,并通过模态框实例的componentInstance传递数据:

onOne(content, info: { Id: any; Name: any }) {
  // 打开模态框,可添加配置项(如size、backdrop等)
  const modalRef = this.modalService.open(content, {
    // 示例配置:size: 'lg', backdrop: 'static'
  });
  // 将info对象赋值给模态框的上下文,供模板使用
  modalRef.componentInstance.data = info;

  modalRef.result.then((result) => {
    this.closeResult = `Closed with: ${result}`;
  }, (reason) => {
    this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
  });
}

3. 在模态框模板中绑定数据

确保你的模态框模板(#content)通过let-data接收传递过来的数据,并在输入框中展示:

<ng-template #content let-data>
  <div class="modal-header">
    <h4 class="modal-title">操作弹窗</h4>
    <button type="button" class="close" aria-label="Close" (click)="modalRef.dismiss('关闭')">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <div class="form-group">
      <label>ID:</label>
      <input type="text" class="form-control" [value]="data.Id" readonly>
    </div>
    <div class="form-group">
      <label>名称:</label>
      <input type="text" class="form-control" [(ngModel)]="data.Name" placeholder="请输入名称">
    </div>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-secondary" (click)="modalRef.close('取消')">取消</button>
    <button type="button" class="btn btn-primary" (click)="modalRef.close('保存')">保存</button>
  </div>
</ng-template>

关键说明

  • let-data是模板上下文的变量名,对应TS中modalRef.componentInstance.data = info里的data,可以自定义名称(比如let-item,对应componentInstance.item = info)。
  • 如果需要双向绑定Name值,确保你的组件中已经导入了FormsModule(在app.module.ts中),否则[(ngModel)]会失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:12:12