Angular 5嵌套ng使用1维数组

时间:2018-03-23 13:03:23

标签: arrays angular ngfor

很抱歉没有给出一个使用示例,但我不确定如何创建codepen angular 5示例。无论如何。我想知道是否可以使用* ngFor重复此数组,但只显示一次值(没有重复)。检查按钮的示例图像,看它应该是什么样子。这个阵列有可能吗?也许使用管道或类似的东西?

enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

可能的解决方案:

首先构建数组:

this.array = [
    {level1: "1", level2: "1.1", level3: "1.1.1"},
    {level1: "1", level2: "1.1", level3: "1.1.2"},
    {level1: "1", level2: "1.2", level3: "1.2.1"}
];

this.fa = {}
this.array.forEach(obj => {
    if(!this.fa[obj.level1]) this.fa[obj.level1] = {};
    if(!this.fa[obj.level1][obj.level2]) this.fa[obj.level1][obj.level2] = [];
    this.fa[obj.level1][obj.level2].push(obj.level3)
})

假设您只有3个级别。然后你将得到以下结构:

{
    "1": {
        "1.1": [
            "1.1.1",
            "1.1.2"
        ]
    }
}

然后在模板中迭代:

<div *ngFor="let i of Object.keys(fa)">
    {{i}}
    <div *ngFor="let j of Object.keys(fa[i])">
        {{j}}    
        <div *ngFor="let k of fa[i][j]">
            {{k}}
        </div>
    </div>
</div>

不要忘记将Object变量绑定到模板,在组件中添加以下行:

Object = Object;

完整示例:

@Component({
    selector: 'app',
    template: `
        <div *ngFor="let i of Object.keys(fa)">
            {{i}}
            <div *ngFor="let j of Object.keys(fa[i])">
                {{j}}
                <div *ngFor="let k of fa[i][j]">
                    {{k}}
                </div>
            </div>
        </div>
    `,
})
export class AppComponent {

    array = [
        {level1: "1", level2: "1.1", level3: "1.1.1"},
        {level1: "1", level2: "1.1", level3: "1.1.2"},
        {level1: "1", level2: "1.2", level3: "1.2.1"}
    ];

    fa = {};

    Object = Object;

    constructor() {
        this.array.forEach(obj => {
            if (!this.fa[obj.level1]) this.fa[obj.level1] = {};
            if (!this.fa[obj.level1][obj.level2]) this.fa[obj.level1][obj.level2] = [];
            this.fa[obj.level1][obj.level2].push(obj.level3)
        })
    }
}