Roka545
Roka545

Reputation: 3626

Print out key/value pairs using HTML and Typescript

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?

Upvotes: 0

Views: 2771

Answers (1)

mickdev
mickdev

Reputation: 2885

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

Upvotes: 5

Related Questions