如何在角度 6 中从示例 json 动态呈现 ul li 值

  • 本文关键字:动态 json ul li html angular
  • 更新时间 :
  • 英文 :


我有一个示例json,我需要使用ul li标签创建一个侧边栏,值来自json。我的 json 结构是这样的。{"filter":{"Category1":{"value":["one","two","three"]},"Category2":{"value":["four","five","six"]}}}.我已经在这里做过 angularjs http://plnkr.co/edit/D8M1U81tVz3UuzjWathk?p=preview,但这在 angular 中不起作用 6.任何人都可以帮我吗,我是角度新手,这是下面的代码

应用.html

<ul *ngFor="(x, y) of items.filter">
<li class="parent"><b>{{x}}</b></li>
<li class="child">
<ul>
<li *ngFor="p of y.value">{{p}}</li>
</ul>
</li>
</ul>

应用程序

export class Heroes {
  let items = {"filter":{"Category1":{"value":["one","two","three"]},"Category2":{"value":["four","five","six"]}}};
}

我建议您在尝试在html组件中使用*ngFor时使用可迭代对象。

所以,这就是我的解决方案:

<ul *ngFor="let parent of (items.filter | keyvalue)">
  <li class="parent">{{ parent.key }}</li>
  <ul *ngFor="let child of (parent.value.value | keyvalue)">
    <li class="child">{{ child.value }}</li>
  </ul>
</ul>

首先,我使用了 angular (https://angular.io/api/common/KeyValuePipe( 的键值管道,之后您可以根据需要迭代 json 对象而无需更改它。

另外,在这里我留下了一个它是如何工作的一个例子(https://stackblitz.com/edit/angular-gqaaet(

您需要更改 json 格式。

items = {"filter":
  [{
    "name":"Category1",
    "value":["one","two","three"]
  },
    {
    "name":"Category2",
    "value":["four","five","six"]
  }
  ]};

.HTML

<ul *ngFor="let item of items.filter">
  <li class="parent"><b>{{item.name}}</b></li>
  <li class="child">
   <ul>
    <li *ngFor="let p of item.value">{{p}}</li>
   </ul>
  </li>
 </ul>

*ng对于迭代协议,您添加的 json 格式具有 map(filter( 的 map(category( 的 map(value( 格式,其中不会获得要迭代的值。

最新更新