Angular 4中使用*ngFor实现HTML表格每行仅显示四列
Hey there! To get your CIDs displayed in rows of 4 in an HTML table with Angular 4, here's a straightforward, easy-to-implement approach:
Step 1: Add a Chunking Helper Function in Your Component
First, we need to split your original cids array into smaller subarrays (each containing up to 4 elements). Add this method to your component class:
getChunkedCids(): Array<Array<any>> { const chunkSize = 4; const chunkedArray = []; for (let i = 0; i < this.cids.length; i += chunkSize) { chunkedArray.push(this.cids.slice(i, i + chunkSize)); } return chunkedArray; }
This function loops through your cids array and slices it into chunks of 4, handling any leftover elements in the final chunk automatically.
Step 2: Update Your Template to Render the Table
Now use nested *ngFor directives in your HTML: one to iterate over each chunk (creating a table row), and another to iterate over each element in the chunk (creating table cells):
<table> <tr *ngFor="let chunk of getChunkedCids()"> <td *ngFor="let item of chunk"> {{ item.Id }} </td> </tr> </table>
Quick Notes:
- If your
cidsarray length isn't a multiple of 4, the last row will just show the remaining elements (no empty cells by default—if you want to add empty placeholder cells, you can adjust the helper function to pad the final chunk, but that's optional). - Make sure your component has the
cidsarray defined, for example:cids: Array<{Id: number}> = [{Id:1}, {Id:2}, {Id:3}, {Id:4}, {Id:5}, {Id:6}, {Id:7}, {Id:8}, {Id:9}];
That's all! This will render your IDs in the exact row structure you requested.
内容的提问来源于stack exchange,提问作者Uday

