Angular在模板中创建递归循环以呈现注释树

时间:2017-09-20 17:33:09

标签: angular ngfor

您好我想将我的应用程序的评论作为评论及其回复呈现,但我不知道如何使用我的数据:

我的数据如下:

"comments": [
  {
    "id": "30",
    "content": "Comment 1",
    "parent": "0",
  },
  {
    "id": "31",
    "content": "Comment 2",
    "parent": "0",
  },
  {
    "id": "32",
    "content": "comment 3",
    "parent": "0",
  },
  {
    "id": "33",
    "content": "sub comment 1-1",
    "parent": "30",
  },
  {
    "id": "34",
    "content": "sub comment 2-1",
    "parent": "31",
  },
  {
    "id": "35",
    "content": "sub sub comment 1-1-1",
    "parent": "33",
  },
  {
    "id": "36",
    "content": "sub comment 1-2",
    "parent": "30",
  }
]

其中parent是指回复评论的ID,因此显示如下:

Comment 1
  sub comment 1-1
    sub sub comment 1-1-1
  sub comment 1-2
Comment 2
  sub comment 2-1
Comment 3

但到目前为止我只按照数据的顺序列出了一个列表

2 个答案:

答案 0 :(得分:2)

是的,@ alexKhymenko是对的。您需要将普通树转换为分层树。您可以使用pipes执行此操作。然后,您可以渲染递归列表以呈现分层树。

管:

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

@Pipe({ name: 'converter' })
export class ConverterPipe implements PipeTransform {
    transform(array: any[], id: string = "id", parentId: string = "parent", rootValue: any = "0"): any[] {
        return this.filterNodes(array, id, parentId, rootValue);
    }
    filterNodes(array: any[], id: string, parentId: string, parentValue: any): any[] {
        return array.filter((node) => {
            return node[parentId] === parentValue;
        }).map((node) => {
            node["items"] = this.filterNodes(array, id, parentId, node[id]);
            return node;
        });
    }
}

标记:

<ng-template #List let-items>
    <ul>
        <li *ngFor="let item of items">
            {{item.content}}
            <ng-container *ngTemplateOutlet="List; context:{ $implicit: item.items }"></ng-container>
        </li>
    </ul>
</ng-template>
<ng-container *ngTemplateOutlet="List; context:{ $implicit: comments | converter }"></ng-container>

请参阅说明这一点的plunk

答案 1 :(得分:1)

1您需要组织数据。你需要迭代列表的主要想法发现父母会向他们添加类似这样的东西

node = {name: 'root', children: [
{name: 'a', children: []},
{name: 'b', children: []},
{name: 'c', children: [
  {name: 'd', children: []},
  {name: 'e', children: []},
  {name: 'f', children: []},
  ]},
 ]};  

然后查看此答案Use component in itself recursively to create a tree

 @Component({
 selector: 'tree-node',
 template: `
 <div>{{node.name}}</div>
 <ul>
   <li *ngFor="let node of node.children">
     <tree-node  [node]="node"></tree-node>
   </li>
 </ul>
 `
})
export class TreeNode {
  @Input() node;
}

他们正在使用树节点组件来创建树。