You can dynamically limit *ngFor by applying ternary operator. Cool suggestion! But if the list is too big, showAll could throw off the users. I personally used a "limit" variable and have a button to expand that limit by 5-10 at a time.
We use the NgFor directive to loop over an array of items and create multiple elements dynamically from a template element. The template element is the element the directive is attached to.
The * character before ngFor creates a parent template. It's a shortcut to the following syntax: template=“ngFor let item of items” .
In *ngFor the * is a shorthand for using the new angular template syntax with a template tag, this is also called structural Directive.It is helpful to know that * is just a shorthand to explicitly defining the data bindings on a template tag. Follow this answer to receive notifications.
This seems simpler to me
<li *ngFor="let item of list | slice:0:10; let i=index" class="dropdown-item" (click)="onClick(item)">{{item.text}}</li>
Closer to your approach
<ng-container *ngFor="let item of list" let-i="index">
<li class="dropdown-item" (click)="onClick(item)" *ngIf="i<11">{{item.text}}</li>
</ng-container>
You can directly apply slice()
to the variable. StackBlitz Demo
<li *ngFor="let item of list.slice(0, 10);">
{{item.text}}
</li>
For example, lets say we want to display only the first 10 items of an array, we could do this using the SlicePipe like so:
<ul>
<li *ngFor="let item of items | slice:0:10">
{{ item }}
</li>
</ul>
This works very well:
<template *ngFor="let item of items; let i=index" >
<ion-slide *ngIf="i<5" >
<img [src]="item.ItemPic">
</ion-slide>
</template>
In addition to @Gunter's answer, you can use trackBy to improve the performance. trackBy takes a function that has two arguments: index and item. You can return a unique value in the object from the function. It will stop re-rendering already displayed items in ngFor. In your html add trackBy as below.
<li *ngFor="let item of list; trackBy: trackByFn;let i=index" class="dropdown-item" (click)="onClick(item)">
<template [ngIf]="i<11">{{item.text}}</template>
</li>
And write a function like this in your .ts file.
trackByfn(index, item) {
return item.uniqueValue;
}
You can dynamically limit *ngFor
by applying ternary operator.
Example 1 -
<div *ngFor="let item of (showAllFlag ? list : list.slice(0,2))" >
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With