How to use a function in the component In Angular
In this approach, we will create a function that returns a subset of elements from the list. We will define the function in the component typescript file, and then use the function in the html template. This function will internally use the slice javascript method to slice the elements, from start to end index, and return those elements as a list.
Example: In this example, we will add a getLimitedItems function inside the app.component.ts file, that takes in a start index, and an end index, and returns the items between those indices. Then, we will use the getLimitedItems function insde the html template to get the first 5 items from the items list.
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]; getLimitedItems(startIndex: number, endIndex: number): number[] { return this .items.slice(startIndex, endIndex); } } |
HTML
<!-- app.component.html --> < div * ngFor = "let item of getLimitedItems(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.
Contact Us