[英]How to use ngFor with complex json in angular to render ul li data
我有一個帶有一些 ul 和 li 的簡單 html 視圖。 但是我需要在代碼中使用數組“jsonarray”來獲得與 ngfor 相同的結構。這是https://stackblitz.com/edit/angular-eigvsq?file=src%2Fapp%2Fapp.component.ts下面的代碼
<div>
<ul>
<h5>Red</h5>
<li>1</li>
<li>2</li>
<li>3</li>
<h5>Blue</h5>
<li>4</li>
<li>5</li>
<li>6</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 = {
id: "0001",
Red: [
{ id: "1001", Order: 1 },
{ id: "1002", Order: 2 },
{ id: "1003", Order: 3 }
],
Blue: [
{ id: "5001", Order: 4 },
{ id: "5002", Order: 5 },
{ id: "5005", Order: 6 }
]
};
ngOnInit() {}
}
<div>
<ul>
<ng-container *ngFor="let data of jsonarray|keyvalue: originalOrder">
<ng-container *ngIf="data.key !== id">
<h5>{{data.key}}</h5>
<ng-container *ngFor="let fields of data.value">
<li>{{fields.Order}}</li>
</ng-container>
</ng-container>
</ng-container>
</ul>
</div>
工作堆棧閃電戰:-
https://stackblitz.com/edit/angular-ge4vjn?file=src/app/app.component.html
首先,您只需要保留要在模板中顯示的值,我的意思是從您的jsonarray屬性中刪除id: '0001'
字段。 然后,在模板中,您可以使用鍵值pipe :
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.