本文介绍了在Angular 2 * ngFor的array/json渲染中将json深度嵌套到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想列出角度为2 * ngFor的以下json的状态和类型.家长属性也应呈现.

I want to list states and types of the following json with angular 2 *ngFor. The parental properties also should be rendered.

var test= {
  '192-168-0-16':{
    'ac395516-96d0-4533-8e0e-efbc68190e':{
      'state':  "none",
      'typ': "test"
    },
    'ac395516-96d0-4533-8e0e-efbc68190e':{
      'state':  "none",
      'typ':  "dummy"
    }
  },
  '222-21-12-12': {
    'ac395516-96d0-4533-8e0e-efbc68190e': {
      'state': "none",
      'typ': "none"
    }
  }

角度2:

<div *ngFor='#s of test'> <!-- also other properties should be visible -->
   <div *ngFor='#t of s'>
      {{t.state}} {{t.typ}}
   </div>
</div>

这当然是行不通的.没有很多数据转换就可以吗?我不确定如何获取json数组.

Of course this does not work. Is it possible without many data transforms? I am not sure how to get arrays of arrays of my json.

推荐答案

您需要将数组与ngFor一起使用.如果要在此级别使用对象,则应考虑使用自定义管道.

You need to use array with ngFor. If you want to use objects at this level, you should consider to use a custom pipe.

有关更多详细信息,请参见以下答案:

See this answer for more details:

基于此,我将以这种方式重构您的代码:

Based on this, I would refactor your code this way:

<div *ngFor='#s of (test | keyValues)'>
  <div *ngFor='#t of (s.value | keyValues)'>
   {{t.value.state}} {{t.value.typ}}
  </div>
</div>

具有以下管道:

@Pipe({name: 'keyValues'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]);
    }
    return keys;
  }
}

这篇关于在Angular 2 * ngFor的array/json渲染中将json深度嵌套到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:37