I have a requirement to access the value of array item by index in ngFor directive angular
Let say i have entityList array.i also have columnNames array which gives me number of td's to generate. so columnNames acts as a table header and entityList has data for it to display in tabular format.
entityList{
"Id": 1,
"Name": "Admin",
}
{
"Id": 2,
"Name": "Finance",
}
columnNames{
"Id",
"Name",
}
<table class="table">
<thead>
<tr>
<th *ngFor="let column of columnNames" scope="col">
{{column}}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let entity of entityList">
<td *ngFor="let column of columnNames;let i = index">
{{entity[i]}}
</td>
</tr>
</tbody>
</table>
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>
CodePudding user response:
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
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>
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.