简体   繁体   中英

Angular 2 show/hide wrap tag in ngFor over even/odd items

I have 2 column list. Is it possible to add if array element is odd element and to close tag if it is even element.

<ng-container ngFor="let item of items; let odd=odd;">
  <!-- if odd -->
    <div class="item-wrapper">
  <!-- /if -->

  <div class="item">{{item.name}}</div>

  <!-- if !odd -->
    </div>
  <!-- /if -->
</ng-container>

In knockout.js i can do it like this:

<!-- ko foreach: items -->
  <!-- ko if: $i % 2 !== 0 -->
    <div class="item-wrapper">
  <!-- /ko -->

  <div class="item">{{items.name}}</div>

  <!-- ko if: $i % 2 === 0 -->
    </div>
  <!-- /ko-->
<!-- /ko-->

Final result of layout should be:

<div class="item-wrapper">
   <div class="item">#NAME_1</div>
   <div class="item">#NAME_2</div>
</div>
<div class="item-wrapper">
   <div class="item">#NAME_3</div>
   <div class="item">#NAME_4</div>
</div>
@Pipe({name: 'split'})
export class BundlePipe implements PipeTransform {
  transform(val, size) {
    if(!size || !val || !val.length) {
      return val;
    }
    var result = [[]];
    var row = 0;
    for(int i = 0; i < val.length; i++) {
      result[row].push(val[i]);
      if(i % row === 0) {
        row++;
      }
    }
  }
}
<ng-container ngFor="let item of items | split:2; let odd=odd;">
  <div class="item-wrapper"></div>
    <div *ngFor="let p of item" class="item">{{item.name}}</div>
  </div>
</ng-container>

Caution - not tested - just to demonstrate the idea

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM