来自Hierarchal数据的Angular 2渲染平面列表

时间:2017-05-15 16:11:54

标签: angular ngfor

Angular 2 中工作,我有以下数据:

let nodes = {
  name: 'ABC Product',
  children: [
    {
      name: 'XYZ Product',
      children: [
        {
          name: 'GHI Product',
          children: []
        },
      ]
    },
    {
      name: 'DEF Product',
      children: []
    },
  ]
}

(真实数据有更多字段)

我需要在一个平面列表中呈现所有产品:

<ul>
  <li>Level 1: ABC Product</li>
  <li>Level 2: DEF Product</li>
  <li>Level 2: XYZ Product</li>
  <li>Level 3: GHI Product</li>
</ul>

请注意,每个级别都需要按name排序。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

您可以在渲染之前准备数据,如:

function flatten(arr: any[], property: string, childrenProperty: string, level: number = 1, dict: any = {}) {
  return arr.reduce((acc, cur) => {
    dict[level] = [...dict[level] || [], { level, data: cur.name }];
    flatten(cur[childrenProperty], property, childrenProperty, level + 1, dict)
    return dict;
  }, dict);
}

...
export class AppComponent {
  nodes = {
    name: 'ABC Product',
    children: [
      {
        name: 'XYZ Product',
        children: [
          {
            name: 'GHI Product',
            children: []
          },
        ]
      },
      {
        name: 'DEF Product',
        children: []
      },
    ]
  };

  flattenNodes: any[];

  ngOnInit() {
    let dict = flatten([this.nodes], 'name', 'children');
    this.flattenNodes = Object.keys(dict).sort((a: any, b: any) => a - b).reduce((acc, cur) => {
      return [...acc, ...dict[cur].sort((a, b) => (a.data < b.data) ? -1 : (a.data > b.data) ? 1 : 0)];
    }, [])
  }
}

<强> Plunker Example

另见