How to repeat HTML element multiple times using ngFor based on a number?
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() {
}
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 >
< 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: '
<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() {
}
numSequence(n: number): Array<number> {
return Array(n);
}
}
|
Output:
Last Updated :
24 Jun, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...