0

I have a key/value pair object in Typescript:

myFields: { [key: string]: string } = {};

I'm trying to create a grid that lists each key next to their value e.g.

name: John
lastname: Smith
age: 40

I know how to make the grid, but I'm not sure how to get each key name and value.

    <div *ngIf="myFields" class="fields-grid-container">
        <div *ngFor="let field of myFields" class="fields-grid-item">
            {{field}}
        </div>
    </div>

This is what I currently have but nothing displays. What's the proper way to print a key/value pair array in html? Would it be better to create a string array and build each string element as the key + value and use that instead?

1
  • 1
    NgForOf expects iterator give it result of object.entries or prepare the object in other manner beforehand. Commented Jun 25, 2019 at 17:21

1 Answer 1

5

You can use the pipe KeyValuePipe

<div *ngFor="let item of someObject | keyvalue">
  {{item.key}}: {{item.value}}
</div>

Stackblitz example : https://stackblitz.com/edit/angular-2xs6zn?file=src/app/app.component.html

Sign up to request clarification or add additional context in comments.

1 Comment

Note this is valid from Angular 6.1 and later. See blog.angular.io/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.