
Angular ngFor example
In Angular, *ngFor is a structural directive used to iterate over a collection (such as an array or list) and generate HTML elements for each item in the collection. It's a fundamental tool for dynamically rendering repeated content in Angular templates.
Angular ngFor Basic example
import { Component } from '@angular/core';
@Component({
selector: 'app-ng-for-example',
template: `<div *ngFor="let item of itemList">
<p>{{item}}</p>
</div>`,
})
export class NgForExampleComponent {
itemList: Array<any> = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5']
}
In this example, ngFor is used to iterate through each item in the Array.
"let item" declares a local template variable (item) that represents
the current item in the iteration.
This variable can be used within the loop.
Angular ngFor example with Index
import { Component } from '@angular/core';
@Component({
selector: 'app-ng-for-example',
template: `<div *ngFor="let item of items; let i = index">
<p>{{ i + 1 }}. {{ item }}</p>
</div>`,
})
export class NgForExampleComponent {
itemList: Array<any> = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5']
}
In this example, the "let i = index" syntax assigns the current
item's index to the "i" variable.
The content of each element is a combination of the index and the item's value.