Angular在模板中创建递归循环以呈现注释树 [英] Angular create a recursive loop in template to render comments tree

查看:58
本文介绍了Angular在模板中创建递归循环以呈现注释树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将应用程序的注释呈现为注释及其答复,但是我不知道如何处理数据:

Hi I want to render the comments of my applications as comments and its reply's but I dont have idea on how to do it with my data:

我的数据如下:

"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,因此应显示为:

where parent refers to the id of the comment that reply, so it shoold be shown like:

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

但是直到现在,我只按我的数据顺序列出一个列表

but until now i only have a list in the order of my data

推荐答案

是的,@ alexKhymenko是正确的.您需要将普通树转换为分层树.您可以使用管道来执行此操作.然后,您可以呈现一个递归列表以呈现您的层次树.

Yes, @alexKhymenko is right. You need to convert your plain tree to a hierarchical tree. You can use pipes to do this. Then, you can render a recursive list to render your hierarchical tree.

管道:

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 进行说明.

这篇关于Angular在模板中创建递归循环以呈现注释树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆