【问题标题】:Access value of array by its index in Angular ngFor directive通过 Angular ngFor 指令中的索引访问数组的值
【发布时间】:2021-10-14 16:52:38
【问题描述】:

我需要通过ngFor指令角度中的索引访问数组项的值

假设我有 entityList 数组。我还有 columnNames 数组,它给了我要生成的 td 数量。所以 columnNames 充当表头,entityList 有数据供它以表格格式显示。

{
    "Id": 1,
    "Name": "Admin",
}
{
    "Id": 2,
    "Name": "Finance",
}


<tr *ngFor="let entity of entityList">
  <td *ngFor="let column of columnNames;let i = index">
    {{entity[i]}}
  </td>
</tr>

我知道我可以像下面那样做,但是我想使用索引而不是名称来打印值。

<tr *ngFor="let entity of entityList;let i = index">
    {{entity.Id}}
    {{entity.Name}}
</tr>

【问题讨论】:

  • 要打印实体的所有属性吗?
  • entity[i] 不是一个数组 - 即使您使用 entityList 而不是 entity 它也是一个对象,即使 i = 0 表示 entityList[i] 表示数组中的第一个对象 @ 987654329@ 你可以做 - 但对我没有任何合乎逻辑的目的
  • 我知道这一点,但是您希望通过entry[i] 访问什么?就像你刚才说的,它是一个具有属性而不是索引的对象
  • 我已将问题编辑为更有用。所以基本上我想要一个解决方案,以便我可以通过索引而不是名称访问 entityList 的属性。有哪些方法可以实现?
  • 我创建了一个答案,我们可以继续努力为您找到解决方案

标签: angular ngfor


【解决方案1】:

通过索引访问条目的属性是不可能的,因为它不是数组而是对象。要获得类似的行为,您可以做的是它的属性及其键。

ts

  keys = Object.keys;

  entityList = [
    { id: 1, name: 'Admin' },
    { id: 2, name: 'Finance' }
  ];

html

<div *ngFor="let entity of entityList;">
    <span>
        {{ entity[keys(entity)[0]] }} // here you can access the keys index
    </span>
</div>

基本上这个想法是在一个数组中获取属性键,选择第一个/第二个,然后通过这个键访问 objects 属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 2021-03-10
    相关资源
    最近更新 更多