In Angular ngFor is directive which accomplishes the motive of displaying repeated or list of contents with least lines of code, this serves the same purpose as for loops in conventional programming languages.
We can print repeated lines of content based on a number using the javascript/typescript function Array() which will generate a list of number from 0 to n-1. We traverse this list to produce n repeated lines of content.
Example 1:
Demo.Component.ts
import { Component, OnInit } from '@angular/core' ; @Component({ selector: 'app-demo' , templateUrl: './demo.component.html' , styleUrls: [ './demo.component.css' ] }) export class DemoComponent implements OnInit { constructor() { } ngOnInit() { } //function to return list of numbers from 0 to n-1 numSequence(n: number): Array<number> { return Array(n); } } |
Demo.Component.html
< mat-card class = "example-card" > < mat-card-header > < h2 >Sequence of Numbers from 0 to 5</ h2 > </ mat-card-header > < mat-card-content > <!-- n traverses through a list of [0, 1, 2, 3, 4, 5] i.e 0 to 5 i stores the index in each iteration --> < span *ngFor="let n of numSequence(6); let i = index ;">{{i}} </ span > </ mat-card-content > </ mat-card > |
Output:
Example 2:
Inserting template in typescript file and repeating the same element 6 times.
Demo2.component.ts
import { Component, OnInit } from '@angular/core' ; @Component({ selector: 'app-demo' , //template encapsulated within the component ts file // instead of separate template(html) template: ' <mat-card class="example-card" > <mat-card-header class="example-header"> <h2 >Repeated neveropen</h2 > </mat-card-header> <mat-card-content> <ul> <!--n traverses through a list of [0, 1, 2, 3, 4, 5] i.e 0 to 5 prints neveropen for 6 times --> <li example-card-text *ngFor="let n of numSequence(6)"> <b>neveropen</b></li> </ul> </mat-card-content> </mat-card> ' , styleUrls: [ './demo.component.css' ] }) export class DemoComponent implements OnInit { constructor() { } ngOnInit() { } //function to return list of numbers from 0 to n-1 numSequence(n: number): Array<number> { return Array(n); } } |
Output: