![](/img/trans.png)
[英]How to manipulate json initialised with key into ngFor in angular 8
[英]How to manipulate the key of array of object into ngfor in angular 8
我有一個對象數組,需要根據 static html 使用 ngFor 進行操作。我已經嘗試過但沒有工作,所以我評論了。“mainitem”的值將作為標題出現,“Seconditem”的鍵將出現在 li 標簽內.這是下面的代碼和演示https://stackblitz.com/edit/angular-eigvsq?file=src%2Fapp%2Fapp.component.ts
<!--
<div>
<ul>
<ng-container *ngFor="let item of jsonarray | keyvalue">
<h5>{{item.key}}</h5>
<li *ngFor="let subItem of item.value">
{{subItem.Order}}
</li>
</ng-container>
</ul>
</div>
-->
<div>
<ul>
<h5>My item 1</h5>
<li>createddate</li>
<li>enddate</li>
<h5>My item 2</h5>
<li>origindate</li>
<li>startdate</li>
</ul>
</div>
import { Component, OnInit } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Angular";
jsonarray = [
{
mainitem: "My item 1",
Seconditem: {
createddate: "30-01-02",
enddate: "30-01-03"
}
},
{
mainitem: "My item 2",
Seconditem: {
origindate: "30-01-04",
startdate: "30-01-05"
}
}
];
ngOnInit() {}
}
我不確定這一點,我在您的代碼中發現了一些問題,例如:
<li *ngFor="let subItem of item.value">
{{subItem.Order}}
</li>
我似乎無法在您的項目中找到item.value
或.Order
但我認為你想多了。 (我認為)
嘗試這個:
<div>
<ul>
<li *ngFor="let item of jsonarray">
<h5>{{item.mainitem}}</h5>
<ng-container *ngFor="let subItem of item.Seconditem | keyvalue">
{{subItem.key}} - {{subItem.value}}
</ng-container>
</li>
</ul>
</div>
這是一個可以使用的模板:
<div>
<ul>
<ng-container *ngFor="let item of jsonarray">
<h5>{{item.mainitem}}</h5>
<li *ngFor="let subItem of item.Seconditem | keyvalue">
{{subItem.key}} - {{subItem.value}}
</li>
</ng-container>
</ul>
</div>
鏈接到工作 stackblitz: https://stackblitz.com/edit/angular-uc15fx?file=src%2Fapp%2Fapp.component.html
試試這個。 我提供了兩種用於渲染內部 li 的選項。 您可以選擇適合您需要的一種。
HTML
<ng-container *ngFor="let item of jsonarray"> <h5>{{item.mainitem}}</h5> <li *ngFor="let key of getKeys(item.Seconditem)"> {{item.Seconditem[key]}} </li> <br> <li *ngFor="let value of getValues(item.Seconditem)"> {{value}} </li> </ng-container>
在 TS 中添加這些功能
public getKeys(data){ return Object.keys(data); } public getValues(data){ return Object.values(data); }
我在這里展示的方法使您的 HTML 超級簡單和易於管理,並且通常是處理具有非統一鍵的 JSON 對象的推薦方法。 因為,它總是建議使用JS 進行數據操作,讓 HTMl只處理 display 。 此外,我們使用Object class 這是 Javascript 本身提供的超級強大的工具。 它帶有大量其他有用的函數(entries() 是另一個很棒的 function,它以數組的形式返回鍵和值!這對你也很有用)。 https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_Objects/Object
希望這可以幫助。 如果您有任何問題或疑問,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.