如何为每三次迭代增加角度6的ngf值

  • 本文关键字:增加 ngf 迭代 三次 angular
  • 更新时间 :
  • 英文 :


如何在ngFor中每三次迭代增加一个值

我想在angular ngfor中实现这样的目标,如何做到这一点


我正在使用下面这样的对象数组,我正在使用ngfor 循环tempArr[]

tempArrA = ['item a', 'item b', 'item c', 'item d', 'item e', 'item f', 'item g', 'item h','item i', 'item j', 'item k', 'item l','item m', 'item n', 'item o', 'item p'];
tempArrB = ['item f', 'item g', 'item h','item i', 'item j'];
tempArrC = [ 'item j', 'item k', 'item l','item m', 'item n', 'item o', 'item p'];
tempArr:any = [
{ 
name: "one",
items: this.tempArrA
},
{ 
name: "two",
items: this.tempArrB
},
{ 
name: "three",
items: this.tempArrC
},
];

项目a-1
项目b-1
c项目-1

项目d--2
项目e-2
项f-2

项目g-3
项目h-3
i项目-3

等等…

您可以通过使用角度管道来使用它。

.html

<div *ngFor="let data of tempArrA; let i = index">
{{data | format : i}}
</div>

.管道

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'format'
})
export class FormatPipe implements PipeTransform {
transform(value: any, args?: any): any {
let d = Math.floor(args / 3) + 1
return value + d;
}
}

此管道将值作为数组值,并将参数作为索引。在管道中,变量被初始化为值=0。然后检查index%3 === 0,此时将初始化值增加1,并通过concatinating返回检查工作链路

https://stackblitz.com/edit/angular-snhcfv?embed=1&file=src/app/app.component.html

通常在angular中,您希望将模型数据映射到视图友好的视图模型中,如下所示:

interface MyItemVm {
value: string;
viewIndex: number;
}
tempArrAVm: MyItemVm[] = tempArrA.map((value, idx) => ({value, viewIndex: Math.floor(idx / 3) + 1}))

然后循环:

<div *ngFor="let itm of tempArrAVm">
{{itm.value}} -- {{itm.viewIndex}}
</div>

对于您的用例来说,这可能有点繁重,但它是这些问题的一般解决方案。之前发布的管道解决方案的修改版本可能适用于您的特定情况。

您可以使用array.reduce将平面数组缩减为二维数组。

组件.ts

// simple array for this example
const source = [1, 2, 3, 4, 5, 6];
this.model = source.reduce((arr, current, idx) => {
const index = Math.floor(idx / 3);
if (arr.length === index) {
arr.push([]);
}
arr[index].push(current);
return arr;
}, []);

component.html

<ng-container *ngFor="let group of model; let i = index">
<div *ngFor="let item of group">
{{item}} -- {{i + 1}}
</div>
</ng-container>

这个简单的例子转换一个长度为6的数组

[ 1, 2, 3, 4, 5, 6 ]

进入长度为2:的2D阵列

[
[ 1, 2, 3 ],
[ 4, 5, 6 ]
]

一旦您的模型的结构符合您的需求,就可以很容易地使用外部索引作为递增3的计数器。如果你需要做更多的工作,你甚至可以将外部索引映射到一个新的对象

对您来说,使用您的模型转换它就足够简单了。

工作演示:https://stackblitz.com/edit/angular-c2hcrz

这是怎么回事

我在这里使用reduce回调函数的前3个参数

(arr, current, idx)

并且用一个空数组调用reduce——第二个参数。

reduce想象成map——它在源数组中循环,并允许您将每个值放在所需的位置。

在回调中:

  • arr是构建并最终返回的新数组
  • current是源数组中循环中的电流值
  • idx是源数组循环中的当前索引

首先,我通过执行Math.floor(idx / 3)来计算出我们应该在新数组中的哪里添加当前索引。这使我们能够在源数组的每三分之一增量中将目标索引增加1。剩下的是相当简单的javascript。

使用对象

将其用于对象是微不足道的。内容在这里并不重要,是原始数组中的索引驱动了分组:

const source = [
{ name: 'One', id: 1 },
{ name: 'Two', id: 2 },
{ name: 'Three', id: 3 },
{ name: 'Four', id: 4 },
{ name: 'Five', id: 5 },
{ name: 'Six', id: 6 }
];
this.objModel = source.reduce((arr, current, idx) => {
const index = Math.floor(idx / 3);
if (arr.length === index) {
arr.push([]);
}
arr[index].push(current);
return arr;
}, []);

最新更新