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

Angular Material Table根据isactive状态动态显示员工号为链接或文本

问题原因分析

你的代码有两个核心问题:

  1. 条件表达式错误:*ngIf="emp.isactive=y" 写法不规范,字符串比较需要加引号,正确写法是 emp.isactive === 'y'(用全等判断更严谨)。
  2. 变量作用域错误:emp 是通过 *matCellDef="let emp" 定义的局部变量,你把 *ngIf 放在了 <td> 外部的容器中,此时 emp 还未被定义,导致无法读取字段值。

正确实现代码

方式一:使用双 *ngIf 分支

<ng-container matColumnDef="Employeenum">
  <th mat-header-cell *matHeaderCellDef>{{"Employee num#"}}</th>
  <td mat-cell data-label="Employee num#" *matCellDef="let emp">
    <a 
      *ngIf="emp.isactive === 'y'"
      tabindex="0" 
      role="link" 
      attr.aria-label="Link for employee number{{emp.empno}}" 
      href="www.abc.com/{{emp.empno}}" 
      target="_blank"
    >
      {{emp.empno}}
    </a>
    <span *ngIf="emp.isactive !== 'y'">{{emp.empno}}</span>
  </td>
</ng-container>

方式二:使用 ngIf-else 模板(更简洁)

<ng-container matColumnDef="Employeenum">
  <th mat-header-cell *matHeaderCellDef>{{"Employee num#"}}</th>
  <td mat-cell data-label="Employee num#" *matCellDef="let emp">
    <ng-container *ngIf="emp.isactive === 'y'; else notActive">
      <a 
        tabindex="0" 
        role="link" 
        attr.aria-label="Link for employee number{{emp.empno}}" 
        href="www.abc.com/{{emp.empno}}" 
        target="_blank"
      >
        {{emp.empno}}
      </a>
    </ng-container>
    <ng-template #notActive>
      {{emp.empno}}
    </ng-template>
  </td>
</ng-container>

关键说明

  • 保持 *matCellDef="let emp" 在 <td> 标签上,确保 emp 变量在整个单元格范围内可用。
  • 用 === 'y' 做严格字符串比较,避免因类型隐式转换导致的判断错误。
  • 将判断逻辑放在 <td> 内部,保证每一行数据都能根据自身的 isactive 字段正确切换显示状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 15:02:23