@for
@for is a new directive introduced in Angular 17 that provides a concise alternative to the traditional *ngFor structural directive for rendering collections in templates. It offers a streamlined approach to iterating over arrays or iterables. This feature aims to enhance the productivity by allowing for more concise template expressions when rendering dynamic content based on collections, ultimately contributing to more readable and maintainable code.
Syntax:
@for (item of items; track $index) {
<element>
{{ item }}
</element>
}
Features of @for:
- Shorter syntax compared to *ngFor.
- Supports iterating over arrays and iterables.
- Does not provide access to the index by default (you can still use the index property if needed).
- No additional properties like trackBy.
Code Example: Open app.component.html and insert below code
<!-- app.component.html -->
<ul>
@for (user of users; track $index) {
<li>
{{ 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.