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.
{
"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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.