Home > Software design >  how to use ngIf with ngFor to limit items to appear
how to use ngIf with ngFor to limit items to appear

Time:05-24

I have this code in angular

``` 
        <div *ngFor ="let product of category?.products; let i=index" >
                <div *ngIf="i<2">
                    <app-item-product[product]="product"></app-item-product>
                </div>
        </div>
```

and i need to show 2 result but its show all the products

CodePudding user response:

You can use slice

<div *ngFor ="let product of (category?.products | slice:0:2); let i=index" >
                <app-item-product[product]="product"></app-item-product>
    </div>

CodePudding user response:

Simply slice your array.

<div *ngFor ="let product of category!.products.slice(0, 2); let i=index">
  <div>
    <app-item-product[product]="product"></app-item-product>
  </div>
</div>

CodePudding user response:

show_more = false;

arr = [1, 2, 3, 4, 5, 6];    


<button (click)="show_more = !show_more">
  <div>{{ show_more ? 'show less' : 'show more...' }}</div>
</button>

<div >
  <div  *ngFor="let x of arr; let i = index">
     <div *ngIf="i < 2 || show_more">
        {{ x }}
     </div>
  </div>
</div>

Here is a stackblitz example, check it out stackblitz

  • Related