Home »
Angular JS
Repeat an HTML element multiple times using ngFor based on a number
By IncludeHelp Last updated : September 4, 2024
In Angular, ngFor is a directive that belongs to the type of structural directive. It is used to repeat a block of HTML for each item in a collection, such as an array or list. It allows you to easily render lists of items dynamically in your templates (or HTML).
Following is the snippet of code for the ngFor directive:
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
Example 1
The following example demonstrates how to repeat an HTML element multiple times using the ngFor:
File: app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
}
File: app.component.html
<h1>Numbers sequence between 1 to 10</h1>
<ul *ngFor = "let a of arr">
<li>{{a}}</li>
</ul>
Output
Following is the output of the above program:
Example 2
Following is another example of doing the same to repeat an HTML element multiple times using ngFor:
File: app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
number(n: number): Array<number> {
return Array(n);
}
}
File: app.component.html
<h1>An HTML content</h1>
<ul *ngFor = "let a of number(5)">
<li>Hello World!</li>
</ul>
Output
The above program produces the following output: