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

Angular12使用@tusharghoshbd ngx-datatable关联字段与状态转换问题

解决方法

前置修正

首先检查你接口数据赋值的逻辑:你贴出的接口返回结构中results下是单数user对象,而你的代码写的是this.userInfoList = data.results.users,如果接口实际返回的是单个用户,需要改为this.userInfoList = [data.results.user],因为表格数据源要求是数组类型,否则会出现渲染异常。如果接口实际返回的是users数组可以忽略此步。


问题1:嵌套对象/数组字段不显示

ngx-datatable默认不支持直接用xxx.xxx的写法读取嵌套字段,数组类型的字段也无法直接读取属性,我们可以用自定义单元格模板的方式实现,和你已有的actionTpl用法一致:

  1. 组件中新增三个模板引用:
// 原有ViewChild保留,新增以下三个
@ViewChild('departmentTpl', {static: true}) departmentTpl: TemplateRef<any>;
@ViewChild('rolesTpl', {static: true}) rolesTpl: TemplateRef<any>;
@ViewChild('activeTpl', {static: true}) activeTpl: TemplateRef<any>;
  1. 修改columns配置,给对应列绑定自定义模板:
this.columns = [
  // 原有id、first_name、last_name列保留不动,修改以下三个列的配置
  {
    key: 'department',
    title: '<div class="blue">Department</div>',
    align: { head: 'left' },
    width: 100,
    sorting: true,
    cellTemplate: this.departmentTpl // 绑定部门模板
  },
  {
    key: 'roles',
    title: '<div class="blue">Roles</div>',
    align: { head: 'left' },
    width: 100,
    sorting: true,
    cellTemplate: this.rolesTpl // 绑定角色模板
  },
  {
    key: 'active',
    title: '<div class="blue">Active</div>',
    align: { head: 'left' },
    width: 100,
    sorting: true,
    cellTemplate: this.activeTpl // 绑定状态模板
  },
  // 原有action列保留不动
]
  1. 在HTML模板中新增三个自定义模板:
<!-- 部门列模板,可选链防止字段为空报错 -->
<ng-template #departmentTpl let-row>
  {{ row.department?.name || '-' }}
</ng-template>

<!-- 角色列模板,将数组中所有角色名用顿号拼接 -->
<ng-template #rolesTpl let-row>
  {{ row.roles?.map(item => item.name).join('、') || '-' }}
</ng-template>

<!-- 状态列模板,转换1/0为友好文本 -->
<ng-template #activeTpl let-row>
  {{ row.active === '1' ? '启用' : '停用' }}
</ng-template>

问题2:active字段转换文本

上述自定义activeTpl已经实现了状态转换逻辑,直接使用即可。如果后续需要修改状态展示规则,直接修改模板里的三元表达式即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 19:09:02