Angular 创建一个包含 5 列的动态表

angular create a dynamic table with 5 columns

提问人:F4b3r 提问时间:10/27/2023 更新时间:10/27/2023 访问量:30

问:

我在 Angular 组件的输入中有一个来自 API 的对象 {key:string,value:string} 列表。 我不知道列表的大小,我必须创建一个表来显示每个项目的键和值。 该表必须动态创建,每 5 个项目我都想创建一个新行,如图所示:enter image description here

任何帮助将不胜感激。 谢谢!

javascript angular html-table 前端

评论

0赞 Scryper 10/27/2023
您应该使用基于项目列表动态创建 HTML 组件。然后,为了能够每 5 个元素创建一个新行,您应该查看 CSS 中的 FlexBox 或 Grid 显示*ngFor

答:

1赞 Ale_Bianco 10/27/2023 #1

您可以使用遍历对象列表并动态创建表。若要确保在每 5 个项目之后创建一个新行,可以使用循环的索引来确定何时开始新行。*ngFor

import { Component } from '@angular/core';

@Component({
  selector: 'app-table',
  template: `
    <table>
      <tr *ngFor="let item of items; let i = index">
        <td>{{ item.key }}</td>
        <td>{{ item.value }}</td>
        <ng-container *ngIf="(i + 1) % 5 === 0; else continueRow"></ng-container>
      </tr>
      <ng-template #continueRow>
        <td colspan="2"></td>
      </ng-template>
    </table>
  `
})
export class TableComponent {
  items = [
    { key: 'Key 1', value: 'Value 1' },
    { key: 'Key 2', value: 'Value 2' },
    // ...
  ];
}