How to use ngfor in ionic html display according to the count of object and determining the rest?

僤鯓⒐⒋嵵緔 提交于 2019-12-11 15:51:13

问题


I am a beginner Ionic developer. I am facing some lack logical concept to display the image according to the no of object and determine the rest accordingly. This might be not so clear. SO here the code

What I want is suppose if I get 5 image from database rest 15 should come from for loop.

 <ion-grid>
      <ion-row no-padding no-margin>
        <ion-col class="food-item" col-4 *ngFor="let number of [0,1,2,3..20]" (click)="addFood()">
              <img src="http://placehold.it/250x200" >
              <div class="card-title" >
                <ion-icon name="add-circle" style="zoom: 2.5;" color="core"></ion-icon>
              </div>
          </ion-col>
      </ion-row>

      <ion-row *ngIf="food" no-padding no-margin text-center>
        <ion-col class="food-item" col-4 *ngFor="let f of food | async " class="card-background-page">
            <img [src]="f.image" (click)="editFood(f)" width="250px" height="80px">
            <div class="card-title">{{f.title}}</div>
        </ion-col>
      </ion-row>
  </ion-grid>

here I have made two rows -- one for displaying database image and another for adding food. But I want one row with ngfor that will display food images and rest will be placeholder image.

Thanks


回答1:


in your component wherever you are getting food, once you get response from API do the following:

while(food.length < 20) {
    food.push({});
}

HTML

<ion-grid>
    <ion-row *ngIf="food" no-padding no-margin text-center>
        <ion-col class="food-item" col-4 *ngFor="let f of food | async " class="card-background-page">
            <ng-template *ngIf="f.image; else noFood">
                <img [src]="f.image" (click)="editFood(f)" width="250px" height="80px">
                <div class="card-title">{{f.title}}</div>
            </ng-template>
            <ng-template #noFood>
                <img src="http://placehold.it/250x200" >
                <div class="card-title" >
                    <ion-icon name="add-circle" style="zoom: 2.5;" color="core"></ion-icon>
                </div>
            </ng-template>
        </ion-col>
    </ion-row>
</ion-grid> 


来源:https://stackoverflow.com/questions/49614420/how-to-use-ngfor-in-ionic-html-display-according-to-the-count-of-object-and-dete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!