I have an array of objects
arr = [
{'name': value},
{'name': value},
{'name': value},
...............
]
Value is svg icon
. I want to display this in the template with *ngFor
<div> arr.name </div>
<svg> arr.value </svg>
Are there ways to do this?
Try this :
arr = [{
'name': 'exp1',
'value': 'exp1'
}, {
'name': 'exp2',
'value': 'exp2'
}]
and in HTML :
<ng-container *ngFor="let item of arr">
<div> {{ item.name }}</div>
<svg> {{ item.value }} </svg>
</ng-container>
assuming 'name' is just a placeholder and the key is actually a variable value, you could do something like:
in controller, map it into something usable:
arr = [
{'name': value},
{'name': value},
{'name': value},
...............
]
mapped = this.arr.map(i => {
let name = Object.keys(i)[0];
let value = i[name];
return {name, value};
});
then in template do exactly what you have:
<ng-container *ngFor="let item of mapped">
<div>{{item.name}}</div>
<svg>{{item.value}}</svg>
</ng-container>
Create function to getKey() and getValue() in object in .ts
getKey(object)
{
let keys= Object.keys(object);
return keys[0];
}
getValue(object)
{
let keys= Object.keys(object);
return object[keys[0]];
}
In HTML
<ng-container *ngFor="let item of arr | keyvalue">
<div>{{getKey(item.value)}}</div>
<svg>{{getValue(item.value)}}</svg>
</ng-container>
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.