How to repeat HTML element multiple times using ngFor based on a number?
Last Updated :
24 Jun, 2020
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
javascript
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
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
javascript
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 GeeksforGeeks</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 GeeksforGeeks for 6 times -->
<li example-card-text
*ngFor="let n of numSequence(6)">
<b>GeeksforGeeks</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: