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

ngx-admin中ng2-smart-table自定义按钮获取行数据传值给模态框

ng2-smart-table自定义按钮传递行数据到模态框实现方案

实现原理

ng2-smart-table的自定义渲染列组件会自动接收当前行数据作为输入属性,配合Nebular对话框服务自带的context传参能力,不需要额外做跨组件通信就能完成数据传递。


具体修改步骤

1. 调整自定义按钮组件NbListComponent

首先从Angular核心引入Input装饰器,声明rowData输入属性接收表格自动注入的当前行完整数据,打开模态框时通过dialog配置的context字段传入需要的bindedSn值:

import { Component, Input, OnInit } from '@angular/core';
import { NbDialogService } from '@nebular/theme';
// 替换成你项目里AffectTPEComponent的实际引入路径
import { AffectTPEComponent } from './affect-tpe/affect-tpe.component';

@Component({
  selector: 'ngx-nb-list',
  template: `
    <button nbButton size="small" status="primary" (click)="openModal()">打开模态框</button>
  `
})
export class NbListComponent implements OnInit {
  // 固定写法,ng2-smart-table会自动把当前行完整数据赋值给这个属性
  @Input() rowData: any;

  constructor(private dialogService: NbDialogService) {}

  ngOnInit(): void {}

  openModal() {
    this.dialogService.open(AffectTPEComponent, {
      closeOnBackdropClick: true,
      // context里的属性会自动注入到模态框组件的同名@Input属性中
      context: {
        bindedSn: this.rowData.bindedSn
      }
    });
  }
}

2. 模态框组件AffectTPEComponent接收参数

在模态框组件里声明和context key同名的@Input属性,就可以直接拿到传入的行数据:

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'ngx-affect-tpe',
  template: `
    <nb-card>
      <nb-card-header>操作</nb-card-header>
      <nb-card-body>
        当前行bindedSn值:{{ bindedSn }}
      </nb-card-body>
    </nb-card>
  `
})
export class AffectTPEComponent implements OnInit {
  // 和dialog context里的key保持一致,自动接收传值
  @Input() bindedSn: string;

  ngOnInit(): void {
    // 这里可以直接使用拿到的bindedSn做后续业务逻辑
    console.log('接收到的行数据bindedSn:', this.bindedSn);
  }
}

注意事项

  • 删掉你原来bindedSn列配置中valuePrepareFunction里给this.bnsn全局变量赋值的代码:这个函数在表格每一行渲染时都会执行,会反复覆盖全局变量,完全无法准确获取点击行对应的值,属于错误写法。
  • 不需要额外写服务传值、事件广播之类的逻辑,上述两个修改点用的都是组件库原生提供的能力,没有额外依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 11:00:59