【问题标题】:How to implement a configurable table with Angular 2+如何使用 Angular 2+ 实现可配置表
【发布时间】:2018-03-09 22:17:09
【问题描述】:

我正在尝试基于 JSON 配置生成一个表。虽然我可以创建表头 OK,但我不知道如何通过字段名称动态选择行单元格数据。这就是我所拥有的:

columns = [
{
    heading: "Person's Name",
    fieldName = "name"
},
{
    heading: "Person's Age"
    fieldName = "age"
} ];

people = [ 
{
    name: "john",
    age: 25,
    gender: "male"
},
{
    name: "mary",
    age: 18,
    gender: "female"
} ];


<table> 

    <tr>
        <th *ngFor="let column of columns">{{column.heading}}</th>
    </tr>

    <tr *ngFor="let person of people">
        <td *ngFor="let column of columns">{{person.column.fieldName}}</td>
    </tr>

</table> 

显然 {{person.column.fieldName}} 不起作用,即这不会转化为 person.name 和 person.age。

关于如何选择列数据中指定的 fieldName 名称的人员字段有什么想法吗?

【问题讨论】:

  • 好吧,我什至不知道这应该如何工作。你有 2 个完全独立的 ngFor。现在有两种选择。要么确保在您的控制器中它们始终处于正确的顺序,要么添加另一个 ngFor,其中包含每个人 ngFor 中的列
  • 抱歉我的错误 - 我现在更新了代码示例。所以我遇到的问题是如何使用 column.fieldName 从 person 中选择正确的字段。

标签: angular typescript


【解决方案1】:

您可以通过字符串索引器访问对象属性

obj.nameobj["name"]

<table> 

    <tr>
        <th *ngFor="let column of columns">{{column.heading}}</th>
    </tr>

    <tr *ngFor="let person of people">
        <td *ngFor="let column of columns">{{person[column.fieldName]}}</td>
    </tr>

</table> 

【讨论】:

  • 工作请客,谢谢!我应该知道这个 doh!
  • 即使性能不佳,这也应该是公认的答案。另一个接受的答案甚至不起作用。我强烈建议不要使用这种方法,因为您只需要执行大量不需要的 ngFor 循环。
  • 我不确定你为什么说“不需要的 ngFor 循环”,因为它们是需要的? - 还是有更好的选择?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-16
  • 1970-01-01
  • 2017-05-11
  • 2017-05-11
  • 1970-01-01
  • 2016-11-17
  • 1970-01-01
相关资源
最近更新 更多