How can i limit ngFor in Angular HTML?

Viewed 125

i need to ngFor with limit 4 items, but if data < 4, i need to force to loop until 4

Example at this

<img *ngFor="let item of [1,2,3,4]"
    src="assets/images/no-image.jpg"
    style="border-radius: 50%; height:90%;" />
4 Answers

Try this way:

<div *ngFor="let item of list; let i=index">
   <img *ngIf="i<4">{{item.text}}</img>
</div>

Try this way

<ng-container *ngFor="let item of [1,2,3,4] ; let i = index">
   <img *ngIf="i < 4"
    src="assets/images/no-image.jpg"
    style="border-radius: 50%; height:90%;" />
</ng-container>

Since you define your array somewhere in your code, the easiest way would be to slice it there. Otherwise you can use the slice pipe so that you can do it right in your code. See https://angular.io/api/common/SlicePipe

So for you you would just add | slice:0:4 to the end of your ngFor


Edit: Sorry, I guess I should have read more carefully. I wrote a Plunker Demo for this. You can either use the pipe or the component logic solution.

Plunker Demo

Try this way

[src]="imageSrc ? imageSrc  : defaultImage"

Here imageSrc is the src of the image you wants to put and defaultImage is the src of the image if not available. Use this way

<img *ngIf="i < 4">
Related