1

I have been trying out Ionic 2 along with angular 2 and its grid layout system. I'd like to be able to loop through an array of items, but because I want it to be responsive, I need to put every X items in a column and row etc, so that they can collapse if need be. In the original angular it would work like this:

<div class="row" ng-repeat="photo in photos" ng-if="$index % 4 === 0">
<div class="row">
    <div class="col col-50" ng-if="$index < photos.length">
        <!-- Content -->
    </div>

    <div class="col col-50" ng-if="$index + 1 < photos.length">
        <!-- Content -->
    </div> 
</div>

<div class="row">
    <div class="col col-50" ng-if="$index + 2 < photos.length">
        <!-- Content -->
    </div>

    <div class="col col-50" ng-if="$index + 3 < photos.length">
        <!-- Content -->
    </div>
</div>

But I'm not sure how to use *ngFor and *ngIf in angular2? Could someone help with moving this over? Can;t find any examples on the web. Many thanks, David.

lateAtNight
  • 482
  • 4
  • 13

1 Answers1

2

You can use them this way:

<div class="row" *ngFor="#photo of photos;#i=index">
 <template [ngIf]="i % 4 === 0">
    <div class="row">
       <div class="col col-50" *ngIf="i < photos.length">
          <!-- Content -->
     </div>

     <div class="col col-50" *ngIf="i + 1 < photos.length">
       <!-- Content -->
     </div> 
  </div>

  <div class="row">
  <div class="col col-50" *ngIf="i + 2 < photos.length">
        <!-- Content -->
    </div>

    <div class="col col-50" ngIf="i + 3 < photos.length">
        <!-- Content -->
    </div>
 </template>
</div>

You can notice the use of "template" (expanded syntax) since ngIf and ngFor can be used on the same element.

See this doc for more details about the template syntax:

Note that with the very last version of Angular2, "#" just be replacer by "let" in the ngFor expression.

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360