Angular Material Table根据isactive状态动态显示员工号为链接或文本
问题原因分析
你的代码有两个核心问题:
- 条件表达式错误:
*ngIf="emp.isactive=y"写法不规范,字符串比较需要加引号,正确写法是emp.isactive === 'y'(用全等判断更严谨)。 - 变量作用域错误:
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
相关产品推荐
相关产品推荐

