I've been digging around, and found out that I can use the following to use *ngFor over an object:
<div *ngFor="#obj of objs | ObjNgFor">...</div>
where ObjNgFor
pipe is:
@Pipe({ name: 'ObjNgFor', pure: false })
export class ObjNgFor implements PipeTransform {
transform(value: any, args: any[] = null): any {
return Object.keys(value).map(key => value[key]);
}
}
However, when I have an object like this:
{
"propertyA":{
"description":"this is the propertyA",
"default":"sth"
},
"propertyB":{
"description":"this is the propertyB",
"default":"sth"
}
}
I am not quite sure how I can extract 'propertyA' and 'propertyB', so that it is accessible from the *ngFor directive. Any ideas?
UPDATE
What I want to do, is to present the following HTML:
<div *ngFor="#obj of objs | ObjNgFor" class="parameters-container">
<div class="parameter-desc">
{{SOMETHING}}:{{obj.description}}
</div>
</div>
Where something would be equal to propertyA
and propertyB
(this is how the object is structured). So, this would lead to:
propertyA:this is the propertyA
propertyB:this is the propertyB
To iterate object keys using *ngFor in Angular, we can use the keyvalue pipe. to add use the keyvalue with *ngFor . We use it to render entries in objects and maps. And we get the key from the key property and the value from value .
You have to pass the object you want to iterate, and the JavaScript Object. keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.
Loop Object Key Values In Angular Using *NgFor & Angular Keyvalue Pipe. KeyValue pipe released in Angular 6.1 to loop through objects,Maps and arrays. Now by passing KeyValue pipe to *ngFor we can loop through objects key values & maps.
Or instead of creating a pipe and passing an object to *ngFor, just pass Object.keys(MyObject)
to *ngFor. It returns the same as the pipe, but without the hassle.
On TypeScript file:
let list = Object.keys(MyObject); // good old javascript on the rescue
On template (html):
*ngFor="let item of list"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With