简体   繁体   English

使用HTML和Typescript打印出键/值对

[英]Print out key/value pairs using HTML and Typescript

I have a key/value pair object in Typescript: 我在Typescript中有一个键/值对对象:

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

I'm trying to create a grid that lists each key next to their value eg 我试图创建一个网格,列出每个键旁边的值,例如

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? 在html中打印键/值对数组的正确方法是什么? Would it be better to create a string array and build each string element as the key + value and use that instead? 创建一个字符串数组并将每个字符串元素构建为键+值并改而使用它会更好吗?

You can use the pipe KeyValuePipe 您可以使用管道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 Stackblitz示例: https ://stackblitz.com/edit/angular-2xs6zn ? file = src/app/app.component.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM