【问题标题】:recursively create a html-list with angular递归地创建一个带有角度的html列表
【发布时间】:2020-06-22 04:39:51
【问题描述】:

我有一个类似树的数据结构

    {
        name: "name 1",
        childs: [
            {
                name: "name 1.1",
                childs: [
                    {
                        name: "name 1.1.1",
                        childs: []
                    },
                    {
                        name: "name 1.1.2",
                        childs: [
                            {
                                name: "name 1.1.2.1",
                                childs: []
                            }
                        ]
                    },
                    {
                        name: "name 1.1.3",
                        childs: []
                    }
                ]
            },
            {
                name: "name 1.2",
                childs: [
                    {
                        name: "name 1.2.1",
                        childs: []
                    }
                ]
            },
            {
                name: "name 1.3",
                childs: [ ]
            }
        ]
    }
] 

我想把它想象成这样的级联列表

<ul>
            <li>name 1
                <ul>
                    <li>name 1.1
                        <ul>
                            <li>name 1.1.1</li>
                            <li>name 1.1.2
                                <ul>
                                    <li>1.1.2.1</li>
                                </ul>
                            </li>
                            <li>name 1.1.3</li>
                        </ul>
                    </li>
                    <li>name 1.2
                        <ul>
                            <li>name 1.2.1</li>
                        </ul>
                    </li>
                    <li>name 1.3</li>
                </ul>
            </li>           
        </ul>

问题是,我的数据结构没有修复。所以我需要递归地创建我的 HTML 输出,但我不知道如何在 Angular 中做到这一点。在这种情况下,一个简单的 *ngfor 是不够的。有没有可以用来解决这个问题的角度机制?或者有谁知道我该如何处理这个问题?

【问题讨论】:

    标签: html angular


    【解决方案1】:

    试试这样:

    <ul>
      <ng-template #recursiveList let-list>
        <li *ngFor="let item of list">
          {{item.name}}
          <ul *ngIf="item.childs.length > 0">
            <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: item.childs }"></ng-container>
          </ul>
        </li>
      </ng-template>
      <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: list }"></ng-container>
    </ul>
    

    https://stackblitz.com/edit/angular-76qpgf?file=src/app/app.component.html

    【讨论】:

    • 正是我想要的。谢谢你!
    猜你喜欢
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多