Angular 18 @for and @empty For Loop Example
Let's see angular 18 @for and @empty examples in this quick example. I explained simply about angular 18 for loop example. This article goes in detail on angular 18 @for index. Here you will learn angular 18 @for track example. Alright, let us dive into the details.
Angular provides for loop using ngFor but, Angular 18 changed the for loop flow with new syntax. You can use @for and @empty for the for loop in angular 18. You can see one example with output and a new one for loop with index and track.
Let's see the simple example code:
Example:
You can update the following code with the app.component.ts file:
src/app/app.component.ts
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
users = [
{ id: 1, name: 'Hardik Savani' },
{ id: 2, name: 'Vimal Kashiyani' },
{ id: 3, name: 'Harshad Pathak' },
];
}
Here, update the app.component.html file:
src/app/app.component.html
<div class="container">
<!-- New @for loop -->
<ul>
@for (user of users; track user.id) {
<li>{{ user.id }}. {{ user.name }}</li>
} @empty {
<span>Empty list of users</span>
}
</ul>
<!-- Old ngFor loop -->
<li *ngFor="let user of users;">
{{user.id}}. {{user.name}}
</li>
</div>
Output:
You will see the following output:
1. Hardik Savani
2. Vimal Kashiyani
3. Harshad Pathak
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Angular 18 Conditional Statements @if, @else if, and @else Example
- Angular 18 CRUD Application Tutorial Example
- How to Create a Project with App Module in Angular 18?
- Angular 18 Chart JS using ng2-charts Example
- How to Get Current Route in Angular 18?
- Angular 18 Install Font Awesome Icons Example
- How to Integrate Google Maps in Angular 18?
- Angular 18 Stripe Payment Integration Example
- Angular 18 Login with Google Gmail Account Example
- Angular 18 Pagination with NGX Pagination Example
- Angular 18 HttpClient & Http Services Tutorial
- Angular 18 RxJS Observable with Httpclient Example
- Angular 18 File Upload Tutorial Example