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 withtypeId='3'. - Moving the
<thead>outside the*ngForloop means it only renders once, no matter how many type 3 attachments you have. - Using
filter()directly in the*ngForsimplifies the template by only looping through the relevant attachments, so you don't need extrang-containerchecks 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

