*ngFor Directive in Angular
The *ngFor
directive in Angular is used to iterate over a collection and render an element for each item in the collection. This tutorial covers the basics of the *ngFor
directive and how to use it effectively in your Angular applications.
What is the *ngFor Directive?
The *ngFor
directive allows you to loop through an array and create a template instance for each item in the array. This is useful for rendering lists, tables, and other repeated content.
Basic Syntax of *ngFor
The basic syntax for the *ngFor
directive is to prefix an element with *ngFor
followed by an expression that iterates over a collection:
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
export class AppComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
Using Index with *ngFor
You can access the index of each item in the collection by using the index
keyword:
<ul>
<li *ngFor="let item of items; let i = index">{{ i }} - {{ item }}</li>
</ul>
export class AppComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
Using TrackBy with *ngFor
The trackBy
function helps Angular track which items have changed, been added, or been removed when iterating over a collection. This can improve performance, especially for large lists:
<ul>
<li *ngFor="let item of items; trackBy: trackById">{{ item.name }}</li>
</ul>
export class AppComponent {
items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
];
trackById(index: number, item: any): number {
return item.id;
}
}
Using *ngFor with Custom Templates
You can use <ng-template>
to create custom templates for the items being iterated over:
<ul>
<ng-template ngFor let-item [ngForOf]="items" let-i="index">
<li>{{ i }} - {{ item }}</li>
</ng-template>
</ul>
export class AppComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
Combining *ngFor with *ngIf
You can combine *ngFor
with *ngIf
to conditionally render items in a collection:
<ul>
<li *ngFor="let item of items">
<div *ngIf="item.visible">{{ item.name }}</div>
</li>
</ul>
export class AppComponent {
items = [
{ name: 'Item 1', visible: true },
{ name: 'Item 2', visible: false },
{ name: 'Item 3', visible: true }
];
}
Key Points
- The
*ngFor
directive is used to iterate over a collection and render an element for each item in the collection. - Use the
index
keyword to access the index of each item in the collection. - The
trackBy
function helps Angular track changes in the collection, improving performance. - Use
<ng-template>
to create custom templates for the items being iterated over. - Combine
*ngFor
with*ngIf
to conditionally render items in a collection.
Conclusion
The *ngFor
directive is a powerful tool for iterating over collections and rendering dynamic content in Angular. By understanding and using the *ngFor
directive effectively, you can create more flexible and efficient Angular applications. Happy coding!