Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate object keys using *ngFor?

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
like image 768
uksz Avatar asked May 05 '16 08:05

uksz


People also ask

How do you loop an object using ngFor?

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 .

How do I iterate through object keys?

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.

Can we use ngFor for objects?

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.


1 Answers

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"
like image 119
Jorge Avatar answered Oct 23 '22 00:10

Jorge