Angular 在模板中创建递归循环以呈现评论树

Angular create a recursive loop in template to render comments tree

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

我的数据如下:

"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

但直到现在我只有一个按数据顺序排列的列表

1 您需要整理数据。您需要遍历列表的主要思想是找到 parents 将孩子附加到他们身上,就像这样

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

然后检查这个答案

 @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;
}

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

是的,@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