Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

javascript - How to display two table columns per row in Angular 2 loop (Angular2 equivalent of PHP's array_chunk)

How can I achieve the following with Angular 2?

I would like to display data, two columns per row during my foreach. I would like my result to look like the following:

<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>

Table: each row has 2 array items enter image description here

Similar question: How to display two table columns per row in php loop

Plunker with basic idea: https://plnkr.co/edit/LuEYfK?p=preview

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

https://plnkr.co/edit/umL80bh0WKr8aPEueCxZ?p=preview

You can create pipe to get pairs values:

@Pipe({ name: 'pairs' })
export class PairsPipe implements PipeTransform {
  transform(array) {
    return array.reduce((result, item, index) => (
      index % 2 ? result : [...result, [item, array[index + 1]]]
    ), []);
  }
}

add pipe to Module:

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App , PairsPipe],
  bootstrap: [ App ]
})

and use in *ngFor:

 <tr *ngFor="let item of data | pairs">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...