gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:18:02 24 4
gpt4 key购买 nike

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

我的数据如下:

"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

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

最佳答案

是的,@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这说明了这一点。

关于Angular 在模板中创建一个递归循环来呈现评论树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46328408/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com