【问题标题】:Create table columns by *ngFor通过 *ngFor 创建表列
【发布时间】:2021-09-09 15:20:12
【问题描述】:

我尝试在 Angular 中制作表格。如何通过例如*ngFor 创建表列?

我有清单

Data [  
​0: 
data: [  
0: 0
1: 4
2: 4
3: 3
4: 5
5: 1
​​​]
id: 49
label: "Label_1"
​​
1: 
data:[ 
0: 5
1: 0
2: 1
3: 5
4: 0
5: 0
​​​]
id: 50
label: "label_2"

]

---- SECOND ARRAY-----

Array [  
0: "value_"
1: "value_"
2: "value_"
3: "value_"
4: "value_"
5: "value_"
]

我想收到这个:

|   #   |   label_1    |   label_2  |   label_3  |
--------------------------------------------------
|Value1 |       1      |     4      |     7      |        
|Value2 |       2      |     5      |     8      |
|Value3 |       3      |     6      |     9      |
--------------------------------------------------

数据将被附加到“数组”中,我希望这些列是自动创建的。我单击按钮“将数据添加到数组”并创建一个新列。它不一定是ngFor。有人可以帮我做这样的事情吗?

【问题讨论】:

  • 你确定“数字”是这样的吗?不像[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  • 对不起,它是 [[1, 2, 3], [4, 5, 6], [7, 8, 9]] - 已编辑

标签: html angular typescript frontend


【解决方案1】:

一种可能的方法是在 HTML 中使用这样的表格:

<table border="1">

  <thead>
    <th>#</th>
    <th *ngFor="let column of array">
      {{column}}
    </th>
  </thead>

  <tbody>
    <tr *ngFor="let row of values; index as i">
      <td>{{row}}</td>
      <td *ngFor="let column of array; index as j">
        {{numbers[j][i]}}
      </td>
    </tr>
  </tbody>

</table>

第一个ngFor 用于列,第二个用于行,第三个用于值

工作Stackblitz

更新

使用新的数据格式:

<table border="1">

  <thead>
    <th>#</th>
    <th *ngFor="let column of array">
      {{column.name}}
    </th>
  </thead>

  <tbody>
    <tr *ngFor="let row of values; index as i">
      <td>{{row}}</td>
      <td *ngFor="let column of array; index as j">
        {{array[j].numbers[i]}}
      </td>
    </tr>
  </tbody>

</table>

工作Stackblitz

第二次更新

要使字段可编辑,请像这样使用ngModel

<input type="number" class="form-control" [(ngModel)]="array[j].numbers[i]">

Stackblitz

【讨论】:

  • @mat373 没问题,我更新了我的答案。让我知道它是否适合您。
  • @mat373 请 fork 最新的 Stackblitz 并将您的数据添加到其中,然后分享链接。
  • 尝试从docs粘贴示例代码。
  • 代替{{column.name}} 尝试调试目的{{ column | json }} 你得到了什么?
  • 你有什么错误吗?你能在 Stackblitz 上分享你正在使用的真实数据吗?
猜你喜欢
  • 2018-11-16
  • 1970-01-01
  • 2018-12-10
  • 1970-01-01
  • 1970-01-01
  • 2022-08-13
  • 1970-01-01
  • 2017-03-25
  • 2019-12-26
相关资源
最近更新 更多