Angular - Display a list of items with ngFor
Other versions available:
- React: React
- Vue: Vue 3, Vue 2
- ASP.NET Core: Blazor WebAssembly
This is a quick example to show how to display a list of items in Angular with the ngFor directive.
The example simply renders an array of users as rows in a table with <tr *ngFor="let user of users">
.
Here it is in action: (See on StackBlitz at https://stackblitz.com/edit/angular-ngfor-display-items-example)
Example Angular Template with ngFor Directive
The app component template contains some standard html for a heading and table, and inside the table the tr
tag uses the *ngFor
Angular directive to loop over the users
array and render a table row for each user that includes the user name, email and role.
<h3 class="p-3 text-center">Angular - Display a list of items with ngFor</h3>
<div class="container">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Role</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of users">
<td>{{user.firstName}} {{user.lastName}}</td>
<td>{{user.email}}</td>
<td>{{user.role}}</td>
</tr>
</tbody>
</table>
</div>
Example Angular Component with Users Array
The angular app component contains the hardcoded users
array that is rendered with the ngFor
directive in the above template. The component is bound to the template with the templateUrl
parameter of the @Component
decorator.
import { Component } from '@angular/core';
@Component({ selector: 'app', templateUrl: 'app.component.html' })
export class AppComponent {
users = [
{ firstName: 'Frank', lastName: 'Murphy', email: '[email protected]', role: 'User' },
{ firstName: 'Vic', lastName: 'Reynolds', email: '[email protected]', role: 'Admin' },
{ firstName: 'Gina', lastName: 'Jabowski', email: '[email protected]', role: 'Admin' },
{ firstName: 'Jessi', lastName: 'Glaser', email: '[email protected]', role: 'User' },
{ firstName: 'Jay', lastName: 'Bilzerian', email: '[email protected]', role: 'User' }
];
}
Angular ngFor Local Variables - index, first, last, even, odd
It's also possible to set local variables with the ngFor
directive to access the index of the current item, to know if it is the first or last item, and to know if is an even or odd item.
This is how to set all local variables with ngFor
:
<tr *ngFor="let user of users; let i = index; let first = first; let last = last; let even = even; let odd = odd">
...
</tr>
Need Some Angular Help?
Search fiverr for freelance Angular developers.
Follow me for updates
When I'm not coding...
Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!