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

Angular 5表格需求:typeId为3时表头仅显一次,无数据时隐藏整表

Hey there! Let's sort out this table display issue in your Angular 5 app. The main problems right now are that your table header repeats every time an attachment with typeId='3' is found, and the table still shows even when there are no such attachments. Here's how to fix it:

Step 1: Add a helper method in your component

First, create a simple method to check if there are any attachments with typeId='3' — this will help us control whether the table should show at all:

hasType3Attachments(): boolean {
  // Use optional chaining to avoid null/undefined errors
  return this.data?.Data?.Summary?.Attachment?.some(attachment => attachment.typeId === '3') || false;
}

Step 2: Rewrite your table template

Now adjust your template to only render the table when there are type 3 attachments, and make sure the header only appears once:

<!-- Only show the table if there are type 3 attachments -->
<table *ngIf="hasType3Attachments()">
  <!-- Header is rendered once, outside the loop -->
  <thead>
    <tr>
      <th>File</th>
      <th>Description</th>
      <th>Date</th>
      <!-- Add any other header columns you need -->
    </tr>
  </thead>
  <tbody>
    <!-- Loop only through attachments with typeId='3' -->
    <tr *ngFor="let attachment of data.Data.Summary.Attachment.filter(att => att.typeId === '3')">
      <td>{{ attachment.fileName }}</td>
      <td>{{ attachment.description }}</td>
      <td>{{ attachment.date }}</td>
      <!-- Add your other data columns here -->
    </tr>
  </tbody>
</table>

Why this works:

  • The *ngIf="hasType3Attachments()" on the <table> element ensures the entire table is hidden when there are no attachments with typeId='3'.
  • Moving the <thead> outside the *ngFor loop means it only renders once, no matter how many type 3 attachments you have.
  • Using filter() directly in the *ngFor simplifies the template by only looping through the relevant attachments, so you don't need extra ng-container checks inside each row.

If you're worried about Attachment being null/undefined, you can add a fallback to the filter:

<tr *ngFor="let attachment of (data?.Data?.Summary?.Attachment || []).filter(att => att.typeId === '3')">

That should cover both your requirements perfectly!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:51:02