如何使用 Angular 2 实现以下目标?
我想在 foreach 期间显示数据,每行两列。我希望我的结果如下所示:
<table>
<tr><td>VALUE1</td><td>VALUE2</td></tr>
<tr><td>VALUE3</td><td>VALUE4</td></tr>
<tr><td>VALUE5</td><td>VALUE6</td></tr>
</table>
类似问题:How to display two table columns per row in php loop
Plunker 的基本思想:https://plnkr.co/edit/LuEYfK?p=preview
最佳答案
https://plnkr.co/edit/umL80bh0WKr8aPEueCxZ?p=preview
您可以创建管道来获取对值:
@Pipe({ name: 'pairs' })
export class PairsPipe implements PipeTransform {
transform(array) {
return array.reduce((result, item, index) => (
index % 2 ? result : [...result, [item, array[index + 1]]]
), []);
}
}
将管道添加到模块:
@NgModule({
imports: [ BrowserModule ],
declarations: [ App , PairsPipe],
bootstrap: [ App ]
})
并在 *ngFor 中使用:
<tr *ngFor="let item of data | pairs">
关于javascript - 如何在 Angular 2 循环中每行显示两个表列(Angular2 相当于 PHP 的 array_chunk),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41597438/