Implementing the SlicePipe

In this approach, we will use SlicePipe in Angular which returns a subset, or a slice, of elements from a list. It takes the indexes, i.e. start and end index and returns the elements from the start to the end index, with the end index element not included. Here, we will add items array & loop over the items array using the ngFor directive, and limit the items to just 5 using SlicePipe.

Example: This example describes the imiting the ngFor repeat to some number of items in Angular.

Javascript




// app.component.ts
  
import { Component } from '@angular/core';
  
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
}


HTML




<!-- app.component.html -->
<div *ngFor="let item of items | slice:0:5">
     {{ item }}
</div>


Output:

How to limit ngFor repeat to some number of items in Angular ?

In AngularJS, we can use the ngFor directive to loop over a list of items and display them on a webpage. Although, there could be some cases where we don’t want to use all the elements in the list but want to display only a limited number of initial items, or the paginated items from the list. In this article, we will see how to limit the ngFor directive to repeat to some number of items only, along with understanding their basic implementation through the illustrations.

Table of Content

  • Implementing the SlicePipe
  • Using a function in the component

We will explore the above approaches with the help of suitable examples.

Similar Reads

Implementing the SlicePipe

In this approach, we will use SlicePipe in Angular which returns a subset, or a slice, of elements from a list. It takes the indexes, i.e. start and end index and returns the elements from the start to the end index, with the end index element not included. Here, we will add items array & loop over the items array using the ngFor directive, and limit the items to just 5 using SlicePipe....

Using a function in the component

...

Contact Us