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

Angular可复用表格模板中空值替换为“---”且不修改row对象的实现方法

完全可以在app-table-multi-sort-cell-default组件内部实现该需求,不需要修改父组件逻辑,也不需要改动原始row对象,以下是几种实现方案:


方案1:纯模板最简实现(推荐,无需修改TS代码)

直接修改table-multi-sort-cell-default.component.html的插值语法即可:

<!-- table-multi-sort-cell-default.component.html -->
<div>{{ cellData?.[id] ?? '---' }}</div>
<div class="cellSubText secondary-text">{{ cellData?.[subId] ?? '---' }}</div>

语法说明:

  • 可选链运算符?.:避免cellData为null/undefined时抛出访问异常
  • 空值合并运算符??:仅当左侧值为null或undefined时,才会返回右侧的---。如果需要把空字符串''也判定为空值替换为---,可以把??替换为||即可。

方案2:组件TS封装方法(方便统一维护占位符)

如果后续可能调整空值占位符,建议在TS中封装统一方法,避免模板多处修改:

// table-multi-sort-cell-default.component.ts
export class TableMultiSortCellDefaultComponent implements OnInit {
  @Input() cellData:any;
  @Input() id: any;
  @Input() subId:any;
  @Input() columnName: any;
  constructor() { }

  ngOnInit(): void {
  }

  // 新增获取展示值的方法
  getCellValue(key: string): string | any {
    return this.cellData?.[key] ?? '---';
  }
}

模板中直接调用方法即可:

<!-- table-multi-sort-cell-default.component.html -->
<div>{{ getCellValue(id) }}</div>
<div class="cellSubText secondary-text">{{ getCellValue(subId) }}</div>

方案3:全局管道复用(适合全项目多处同类需求)

如果项目中多个组件都有空值替换需求,可以封装全局管道一次定义多处使用:

// empty-placeholder.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'emptyPlaceholder'
})
export class EmptyPlaceholderPipe implements PipeTransform {
  transform(value: any, placeholder: string = '---'): any {
    return value ?? placeholder;
  }
}

在对应模块的declarations数组中声明该管道后,即可在模板中直接调用:

<!-- table-multi-sort-cell-default.component.html -->
<div>{{ cellData?.[id] | emptyPlaceholder }}</div>
<div class="cellSubText secondary-text">{{ cellData?.[subId] | emptyPlaceholder }}</div>
<!-- 支持自定义占位符写法:{{ cellData?.[id] | emptyPlaceholder:'无数据' }} -->

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 23:24:05