How to use slice In Angular
In this approach, we will slice the given Array of objects and then use keyvalue to iterate over the object.
Example: This is another example that illustrates limiting the ngFor loop to 2 iterations.
app.component.html
Javascript
// app.component.ts import { Component, OnInit } from '@angular/core' ; import { KeyValue } from '@angular/common' ; import { Pipe, PipeTransform } from '@angular/core' ; @Component({ selector: 'app-root' , templateUrl: "./app.component.html" , styleUrls: [ './app.component.css' ] }) export class AppComponent { gfg: Array<{ course: string, text: string }> = [ { course: "HTML" , text: "Hyper Text Markup Language" }, { course: "CSS" , text: "Cascade Style Sheet" }, { course: "XML" , text: "Xtensive Markup Language" }, { course: "JS" , text: "Javascript" } ] gfg2: any sliceObject() { this .gfg2 = this .gfg.slice(0, 2) } getObject(obj: any) { return Object.values(obj) } console = console } |
Javascript
// app.module.ts import { NgModule } from '@angular/core' ; import { BrowserModule } from '@angular/platform-browser' ; import { HttpClientModule } from '@angular/common/http' ; import { AppComponent } from './app.component' ; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule, ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
HTML
<!-- app.component.html --> < h2 style = "color: green" >w3wiki</ h2 > < h2 >Limit the ngFor loop to two iterations</ h2 > {{sliceObject()}} < div * ngFor = "let item of gfg2 |keyvalue;" > < b style = "color: red;" >{{item.key}}: </ b > {{getObject(item.value)}} </ div > |
Output:
How to limit the ngFor Loop to Two Iterations in Angular ?
The NgFor is used as a structural directive that renders each element for the given collection each element can be displayed on the page. In this article, we will learn how to Limit the ngFor loop to two iterations.
Table of Content
- Steps for Installing & Configuring the Angular Application
- Project Structure
- Using ngIf
- Using slice