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

Angular 13中Mat Table文件下载图标按需显示问题求助

解决方案

1. 完善TypeScript方法

先补全setFile方法的逻辑,确保URL不存在时返回null,避免绑定无效值:

setFile(url: string): string | null {
  if (url?.trim()) { // 同时处理null、undefined和空字符串场景
    this.DisplayFileUrl = this.congesService.getFilePath(url);
    return this.DisplayFileUrl;
  }
  return null; // URL无效时返回null
}

2. 在HTML中添加条件渲染

给<a>标签加上*ngIf判断,只有当URL有效时才显示下载图标:

</ng-container>
<ng-container matColumnDef="fileUrl">
  <th mat-header-cell *matHeaderCellDef> url </th>
  <td mat-cell *matCellDef="let element"> 
    <a 
      *ngIf="element.fileUrl?.trim()" 
      [href]="setFile(element.fileUrl)" 
      target="_blank"
    >
      <i class="fas fa-file-pdf"></i>
    </a>
  </td>
</ng-container>

可选优化:简化模板逻辑

如果不需要在组件中存储DisplayFileUrl,可以直接在模板调用服务方法,省去组件中的setFile方法:

</ng-container>
<ng-container matColumnDef="fileUrl">
  <th mat-header-cell *matHeaderCellDef> url </th>
  <td mat-cell *matCellDef="let element"> 
    <a 
      *ngIf="element.fileUrl?.trim()" 
      [href]="congesService.getFilePath(element.fileUrl)" 
      target="_blank"
    >
      <i class="fas fa-file-pdf"></i>
    </a>
  </td>
</ng-container>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:20:29