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

Angular 4中使用*ngFor实现HTML表格每行仅显示四列

Solution to Display CIDs in Rows of 4 Using Angular 4 *ngFor

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 cids array 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 cids array 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:05:19