*ngFor
*ngFor is a structural directive in Angular that facilitates the rendering of a collection of items in the template by iterating over an array or an iterable object. It provides a declarative approach to dynamically generate a set of elements based on the elements in the collection. The syntax involves using the *ngFor directive along with a microsyntax that specifies the iteration variable and the source collection. This directive is a built-in feature in Angular and must be imported from the CommonModule or included in the imports array of the respective module or standalone component before it can be utilized in the template.
Syntax:
<element *ngFor="let item of items; let i=index">
<!-- content -->
</element>
Features of *ngFor:
- Supports iterating over arrays, objects, and other iterables.
- Provides access to the current item and its index.
- Allows you to use local variables for the item and index.
- Supports additional properties like trackBy for change detection optimization.
Code Example: Open app.component.html and insert below code
<!-- app.component.html -->
<ul>
<li *ngFor="let user of users; let i=index">
{{ i + 1 }}. {{ user.name }}
</li>
</ul>
Output:
Difference between *ngFor and @for in Angular 17
In Angular, *ngFor and @for are constructs used for iterating over collections and rendering dynamic content, but they differ in their implementation and usage. *ngFor is a structural directive that has been a longstanding feature, while @for is a new shorthand syntax introduced in Angular 17. *ngFor is a more verbose and explicit approach, akin to a tried-and-true tool in your toolbox, whereas @for provides a more concise and streamlined way of achieving the same functionality, resembling a sleek, modern gadget that simplifies the process of rendering dynamic lists or repeating elements.