问题描述
在javascript中,以下情况非常容易,但是在Angular中工作时遇到了一些问题.
The following scenario would be pretty easy in javascript but I got some problems getting it worked in Angular.
我得到了一个像这样的数组:
I got an Array like:
array a = ( "id" = 0, name = random(), column = 1, 2 or 3, blockrow= 1, 2 or 3)
我使用ngFor尝试现在创建一个网格,在此列中所有元素都被分隔为多个列和块.因此,我当前的代码(有效但讨厌).
With ngFor I try to create now a grid there all elements out of a get separated in colums and blocks in this column. So my current code (works but nasty).
<div *ngFor="let a of a">
<template [ngIf]="a.column=='1'">
<div *ngFor="let b of a">
<template [ngIf]="b.blockrow=='1'">
Block 1 in column 1{{b.name}}
</template>
</div>
<div *ngFor="let b of a">
<template [ngIf]="b.blockrow=='2'">
Block 2 in column 1{{b.name}}
</template>
</div>
<div *ngFor="let b of a">
<template [ngIf]="b.blockrow=='3'">
Block 3 in column 1{{b.name}}
</template>
</div>
</template>
</div>
类似的事情我会在每一列上运行.这意味着我循环通过同一数组12次.有什么办法可以使它更美丽吗?
Something like this do I run for every column. Which means I loop trough the same array for 12 times. Is there any way to do it more beautifull ?
推荐答案
在您的组件中,使用JavaScript构建具有 a 元素在正确坐标处的数组数组,然后使用* ngFor内* ngFor:
In your component, use JavaScript to build an array of arrays with the elements of a at the right coordinates, then use *ngFor inside *ngFor:
<div *ngFor="let row of rows">
<div *ngFor="let col of row">
Block {{col.blockrow}} in column {{col.column}} {{col.name}}
</div>
</div>
如果多个块具有相同的坐标,则可能需要第三个* ngFor.
A third *ngFor might be needed if several blocks have the same coordinates.
这篇关于角度2:* ngFor中的* ngFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!