简体   繁体   English

通过 Angular ngFor 指令中的索引访问数组的值

[英]Access value of array by its index in Angular ngFor directive

I have a requirement to access the value of array item by index in ngFor directive angular我需要通过ngFor指令 angular 中的索引访问数组项的值

Let say I have entityList array.假设我有 entityList 数组。 I also have columnNames array which gives me number of td's to generate.我也有 columnNames 数组,它为我提供了要生成的 td 数。 So columnNames acts as a table header and entityList has data for it to display in tabular format.所以 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>

I know I can do it like below , however i want to print the value using index and not by name.我知道我可以像下面那样做,但是我想使用索引而不是名称来打印值。

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

Accessing the properties of entry by an index is impossible since it's not an array but an object.通过索引访问条目的属性是不可能的,因为它不是数组而是对象。 What you can do, to get a similar behaviour is its properties with their keys.您可以做的是获得类似行为的是其属性及其键。

ts ts

  keys = Object.keys;

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

html html

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

Basically the idea is to get the property keys in an array, pick the the first/second one and then access the objects property via this key.基本上这个想法是获取数组中的属性键,选择第一个/第二个,然后通过这个键访问对象属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM