【问题标题】:How to use ngFor with complex json in angular to render ul li data如何在角度中使用带有复杂json的ngFor来渲染ul li数据
【发布时间】:2021-03-23 05:17:13
【问题描述】:

我有一个带有一些 ul 和 li 的简单 html 视图。但是我需要在代码中使用数组'jsonarray'得到与ngfor相同的结构。下面是https://stackblitz.com/edit/angular-eigvsq?file=src%2Fapp%2Fapp.component.ts

的代码

app.component.html

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

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 = {
    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() {}
}

【问题讨论】:

  • 如果你知道你需要ngFor,那你为什么不用ngFor来写呢?或者,你想让别人为你写这篇文章吗?

标签: javascript angular


【解决方案1】:

首先,您只需要保留要在模板中显示的值,我的意思是从 jsonarray 属性中删除 id: '0001' 字段。然后,在模板中可以使用keyvalue 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>

【讨论】:

    【解决方案2】:
    <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

    【讨论】:

      猜你喜欢
      • 2018-08-12
      • 1970-01-01
      • 2016-06-14
      • 1970-01-01
      • 2017-07-01
      • 1970-01-01
      • 2011-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多