How to iterate object keys using *ngFor?

uksz picture uksz · May 5, 2016 · Viewed 27.8k times · Source

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

Answer

Jorge picture Jorge · May 13, 2017

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"