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

Angular中ng2-smart-table自定义组件获取行数据问题求助

问题解决:ng2-smart-table插入新行时自定义组件无法获取其他列临时输入值

问题原因

插入新行的编辑状态下,rowData对应的是初始空数据(尚未保存到数据源),你在temperaturaMaxima和temperaturaMinima输入框中输入的临时值不会自动同步到rowData,这些值暂存于对应列的cell.newValue属性中,直接读取rowData自然拿不到最新输入内容。

解决方案

方案1:通过行对象获取列的临时输入值

利用DefaultEditor继承的row属性,直接获取目标列的单元格对象,读取其临时输入值:

修改自定义组件的test()方法:

test() {
  // 获取最高温度列的单元格及临时值
  const tempMaxCell = this.row.getCell('temperaturaMaxima');
  const tempMaxValue = tempMaxCell.newValue;
  
  // 获取最低温度列的单元格及临时值
  const tempMinCell = this.row.getCell('temperaturaMinima');
  const tempMinValue = tempMinCell.newValue;
  
  alert(`最高温度:${tempMaxValue},最低温度:${tempMinValue}`);
}

方案2:实时同步临时值到rowData(可选)

如果希望rowData能实时同步输入值,可在表格配置中给temperaturaMaxima和temperaturaMinima添加编辑器回调,监听输入变化并更新rowData:

更新表格配置代码:

temperaturaMaxima: {
  type: 'number',
  title: 'Temperatura Máxima',
  editor: {
    onComponentInitFunction: (component) => {
      component.cell.newValueChanges.subscribe((value) => {
        component.rowData.temperaturaMaxima = value;
      });
    }
  }
},
temperaturaMinima: {
  title: 'Temperatura Mínima',
  type: 'number',
  editor: {
    onComponentInitFunction: (component) => {
      component.cell.newValueChanges.subscribe((value) => {
        component.rowData.temperaturaMinima = value;
      });
    }
  }
},
temperaturaMedia: {
  title: 'Temperatura Média',
  type: 'number',
  editor: {
    type: 'custom',
    component: SmartTableEditorFunctionsComponent,
    valuePrepareFunction(instance) {
      instance.save.subscribe();
    },
  },
},

修改后,你原有的test()方法就能直接通过this.rowData.temperaturaMaxima获取实时输入值。

额外提示

  • DefaultEditor已内置cell、row等核心属性,无需额外通过@Input()声明rowData(保留也不影响,但新行初始为空)。
  • 若需自动计算平均温度,可监听两温度列的newValueChanges事件,实时计算并赋值给temperaturaMedia的cell.newValue。

内容的提问来源于stack exchange,提问作者Ítalo Gustavo Araújo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:15:32