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

Angular ng2-smart-table参数传递异常:自定义组件值为undefined

解决ng2-smart-table自定义组件参数传递undefined问题

问题分析

你当前的代码中,valuePrepareFunction返回了{ isActive: cell },但ng2-smart-table并不会自动将这个对象的属性映射到自定义组件的@Input属性上。默认情况下,该函数的返回值会作为组件的value输入(若组件定义了@Input() value),而你的组件只定义了@Input() isActive,因此导致值无法传递,始终为undefined。

解决方案

下面提供两种可行的修复方式:

方式一:通过componentSettings绑定输入属性

直接在列配置中添加componentSettings,明确将isActive绑定到对应的值:

settings = {
  hideSubHeader: true,
  actions: {
    columnTitle: 'Manage',
    add: false,  
    edit: false, 
    delete: false
  },
  columns: {
    status: {
      title: 'status',
      type: 'custom',
      renderComponent: ToggleButtonComponent,
      // 新增componentSettings绑定输入属性
      componentSettings: {
        inputs: {
          isActive: 'cell' // 将cell值绑定到组件的isActive输入
        }
      },
      valuePrepareFunction: (cell) => {
        console.log("cell>>", cell);
        return cell; // 直接返回原始值即可,无需包装成对象
      }
    },
  },
};

方式二:利用onComponentInitFunction手动赋值

通过初始化钩子函数,直接将行数据中的status值赋值给组件的isActive,同时还可以监听组件的输出事件:

settings = {
  hideSubHeader: true,
  actions: {
    columnTitle: 'Manage',
    add: false,  
    edit: false, 
    delete: false
  },
  columns: {
    status: {
      title: 'status',
      type: 'custom',
      renderComponent: ToggleButtonComponent,
      onComponentInitFunction: (instance, row) => {
        // 手动将行数据的status赋值给组件的isActive
        instance.isActive = row.status;
        // 可选:监听组件的切换事件做后续处理
        instance.toggleButtonChange.subscribe((value) => {
          console.log('切换后的值:', value);
          // 这里可以调用服务更新后端数据
        });
      },
      valuePrepareFunction: (cell) => {
        console.log("cell>>", cell);
        return cell;
      }
    },
  },
};

验证修改

修改完成后,重新运行项目,组件的ngOnInit中打印的isActive应该会正确显示服务端返回的true或false,nb-toggle的状态也会对应生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 17:55:05