[英]How to map key and value data to text fields in Angular
我有一個簡單的 JSON 有一個鍵和一個值,兩者都有不同的值。 我想在視圖上顯示每個鍵和值,我不確定如何 go 關於它。 這是我的 json
[
{
"key": "CLT",
"value": "21"
},
{
"key": "HEM",
"value": "3"
},
{
"key": "LIP",
"value": "4"
},
{
"key": "QNS",
"value": "853"
},
{
"key": "SAT",
"value": "24202"
},
{
"key": "SHV",
"value": "229"
},
{
"key": "SNC",
"value": "196"
},
{
"key": "VPL",
"value": "4"
}
]
這是我的 model
export class PTIDS {
key: string;
value: number;
}
我希望能夠在 html 中對它們進行 map
<tbody *ngFor="let central of Centrals">
<tr>
<th>CLT(show key here)</th>
<th>central.CLT(SHOW value here)</th>
</tr>
<th>HEM(show key here)</th>
<th>central.HEM(SHOW value here)</th>
</tr>
<th>LTP(show key here)</th>
<th>central.LTP(SHOW value here)</th>
</tr>
</tbody>
先感謝您
首先要修復的是 model。 PTIDS 值類型是number
但在您的代碼中它是string
。 應該是 20 而不是" 20 " 。
這是工作解決方案:
app.component.ts
centrals: PTIDS[] = [
{
key: "CLT",
value: 21
},
{
key: "HEM",
value: 3
},
{
key: "LIP",
value: 4
},
{
key: "QNS",
value: 853
},
{
key: "SAT",
value: 24202
},
{
key: "SHV",
value: 229
},
{
key: "SNC",
value: 196
},
{
key: "VPL",
value: 4
}
];
app.component.html
<tbody *ngFor="let central of centrals">
<tr>
<th>{{central.key}}</th>
<th>{{central.value}}</th>
</tr>
</tbody>
更新 1:(根據屏幕截圖中提供的 UI 更新代碼)
html
<div class="main">
<div class="box" *ngFor="let central of centrals">
<div>{{central.key}}</div>
<span>{{central.value}}</span>
</div>
</div>
CSS:
.main {
display: flex;
align-items: center;
justify-content: space-between;
}
.box {
background-color: orange;
width: auto;
height: auto;
margin: 10px;
padding: 20px;
border: 1px solid red;
}
這是演示鏈接。
如果可能,請提供有關stackblitz的示例,以便更容易復制。 請嘗試類似:
<div *ngFor="let central of Centrals">
<span>{{central.key}}</span>
<span>{{central.value}}</span>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.