Enrico Nathaniel
Enrico Nathaniel

Reputation: 21

How can i limit ngFor in Angular HTML?

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%;" />

Upvotes: 2

Views: 239

Answers (4)

dasunse
dasunse

Reputation: 3099

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

Upvotes: 0

Eweren
Eweren

Reputation: 277

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

Upvotes: 2

Connect2sky
Connect2sky

Reputation: 337

Try this way:

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

Upvotes: 2

Sayooj V R
Sayooj V R

Reputation: 2363

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>

Upvotes: 2

Related Questions