javascript - 嵌套的 json 需要借助 Angular 以树结构格式动态显示

标签 javascript angular typescript ecmascript-6

我正在使用嵌套的 JSON 寻找以下结果。我无法动态检索/调用模板中的键和值。 Refrence link is attached for detail veiw

Angular 代码

let checklist = {
"CS": [
  {
    "id": "1",
    "name": "A"
  },
  {
    "id": "2",
    "name": "B"
  },
  {
    "id": "3",
    "name": "C"
  }
],
"Comment": [
  {
    "id": "1",
    "name": "D"
  },
  {
    "id": "2",
    "name": "E"
  },
  {
    "id": "3",
    "name": "F"
  }
]
}


<div *ngFor="let item of Checklist | Key">
      {{key}}
 <div>{{item}}</div>
 </div>

期望的结果

enter image description here

最佳答案

使用keyvalue管道循环模板内的对象,使用一些CSS来修改显示,但像下面这样的代码将满足您的需求。

<div *ngFor="let item of checklist | keyvalue">
  <div>
    {{item.key}}
  </div>
  <div>
    <p *ngFor="let eachValue of item.value">
      {{eachValue.name}}
    </p>
  </div>   
</div>

https://stackblitz.com/edit/angular-jgwk8n?file=src%2Fapp%2Fapp.component.html

编辑

对于 Angular 版本 < 6,keyvalue 管道不存在。您可以创建自己的自定义管道,例如:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'customKeyvalue',
  pure: true     // keyvalue pipe is actually impure, which means this value would be false
})
export class CustomKeyvaluePipe implements PipeTransform {

  transform(inputOb: any): any {
    let returnVal = [];
    for (let eachKey in inputOb) {
      returnVal.push({key: eachKey, value: inputOb[eachKey]})
    }
    return returnVal
  }

}

现在,如果您的对象动态更改而不更改其原始引用,那么您必须将上述管道设置为 impure (pure: false)。这样做的缺点是每次更改检测都会触发。

https://stackblitz.com/edit/angular-jgwk8n?file=src%2Fapp%2Fapp.component.html

关于javascript - 嵌套的 json 需要借助 Angular 以树结构格式动态显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55222883/

相关文章:

node.js - NodeJS 中按依赖关系对 TypeScript 文件进行排序

Angular 动画: :leave ( * => void) not working as :enter (void => * ) is working

javascript - Injector 中提供的 Angular 6 通用服务需要另一个应用程序注入(inject)变量

angular - 链接 Angular 4 和 OpenLayers 4

typescript - 类型缩小 : checking variable object key existence when noUncheckedIndexedAccess is true

javascript - 为什么在使用 AJAX 的 View 中加载内联 JavaScript 不好?

javascript - jQuery OnLoad 页面滚动问题

ASP.net 表单复式输入

javascript - 使对象不通过引用传递

javascript - 如何从 ImmutableJS Record 构造函数调用函数