【问题标题】:Display nested object to array in table with ngFor使用 ngFor 在表格中显示嵌套对象到数组
【发布时间】:2019-11-10 13:21:23
【问题描述】:

我有一个数组:

fooData = [
    {value: 1, children: [{value: 2}, {value: 3}, {value: 4}, {value: 5}]},
    {value: 6, children: [{value: 7}, {value: 8}, {value: 9}, {value: 10, children: [{value: 11}]}]},
];

在不更改数组的情况下,如何使用 ngFor 显示它以获得这样的内联表:

 <table>
    <tr><td>1</td></tr>
    <tr><td>2</td></tr>
    <tr><td>3</td></tr>
    <tr><td>4</td></tr>
    <tr><td>5</td></tr>
    <tr><td>6</td></tr>
    <tr><td>7</td></tr>
    <tr><td>8</td></tr>
    <tr><td>9</td></tr>
    <tr><td>10</td></tr>
    <tr><td>11</td></tr>
  </table>

【问题讨论】:

    标签: angular ngfor


    【解决方案1】:

    定义一个 ng-template 元素来显示 value 属性并使用 ng-container 为 children 属性递归激活相同的模板。我已经添加了代码here

    <table>
        <ng-container [ngTemplateOutlet]="common" [ngTemplateOutletContext]="{link:fooData}">
        </ng-container>
    </table>
    
    <ng-template #common let-link='link'>
        <ng-container *ngFor="let data of link">
            <tr>
                <td>{{data.value}}</td>
            </tr>
            <ng-container *ngIf="data.children" [ngTemplateOutlet]="common" [ngTemplateOutletContext]="{link:data.children}">
            </ng-container>
        </ng-container>
    </ng-template>
    

    【讨论】:

    • 10 的 11 个孩子的最后一个值呢?
    • @TSR 检查更新的答案。我会更新最简化的。
    【解决方案2】:

    您需要递归地从数组中提取属性value。一旦你有了它,你将拥有可以循环显示的线性数组。

    这是你的递归 pluck 函数:

    function pluckRecursive(input, prop, collect) {
        collect = collect || [];
    
        if (_.isArray(input)) {
            _.forEach(input, function (value, key) {
                pluckRecursive(value, prop, collect);
            })    
        } else if (_.isObject(input)) {
            _.forEach(input, function (value, key) {
                if (key === prop) {
                    collect.push(value);
                } else {
                    pluckRecursive(value, prop, collect);
                }
            })    
        }
    
        return collect;
    };
    

    使用此函数来提取您的值:

    arrayToDisplay: number[] = pluckRecursive(this.fooData, 'value');
    

    然后显示如下:

     <table>
        <tr *ngFor="let item of arrayToDisplay"><td>{{item}}</td></tr>
      </table>
    

    看看this StackBlitz 插图。

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2017-10-12
      • 2021-03-28
      • 2018-10-14
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      相关资源
      最近更新 更多