首页 > 解决方案 > 如何在角度 8 中将用密钥初始化的 json 操作到 ngFor

问题描述

我有一个用键初始化的json(键可以更改,它是动态的),我需要按照静态html操作成ngFor。我已经尝试过但没有工作,所以我评论了。'mainitem'的值将作为标题'Secondiitem' 的键将出现在 li 标签内。这是下面的代码和演示https://stackblitz.com/edit/angular-ufbwzw?file=src%2Fapp%2Fapp.component.ts

app.component.html

<p>
    Start editing to see some magic happen :)
</p>

<!--<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>
-->
<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>

app.component.ts

import { Component, OnInit } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular";
  jsonarray = {
    "575": [
      {
        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() {}
}

标签: htmlangular

解决方案


<ul>
        <ng-container *ngFor="let item of jsonarray | keyvalue">
           <ng-container *ngFor="let value of item.value">
            <h5>{{value.mainitem}}</h5>
            <li *ngFor="let subItem of value.Seconditem | keyvalue">
                {{subItem.key}} - {{subItem.value}}
            </li>
           </ng-container>
        </ng-container>
    </ul>

工作 Stackblitz:- https://stackblitz.com/edit/angular-kfwv4m?file=src/app/app.component.html


推荐阅读