Angular - List rendering using *ngFor directive

Angular - List rendering using *ngFor directive

In this tutorial, we will learn about how to render a list of items into the dom by using *ngFor directive.

ngFor

In angular, we need to use *ngFor directive to render a list of items into the dom.

The syntax of a *ngFor directive.

v-for="user in users"
<!-- user variable is iterator -->
<!--users is data array-->

Example:

app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  users = [    { id: 1, name: 'ram' },    { id: 2, name: 'gowtham' },    { id: 3, name: 'ooops' },  ];}
app.component.html
<ul>
    <!-- rendering array of users -->
    <li *ngFor="let user of users">{{user.name}}</li></ul>

In the above code, we are looping through the array of users using *ngFor directive where user variable is pointing to the different user on each iteration.

list rendering example ngfor

Accessing the Index

We can also access the item index which we are currently iterating.

app.component.html
<ul>
    <li *ngFor="let user of users; index as userIndex">       {{user.name}} - {{userIndex}}    </li>
</ul>

index is a reserved keyword in angular so that we aliasing userIndex to access the index.

Other things we can do

ngFor directive can also provide us other reserved keywords where it can alias to local variables.

first: boolean: True when the item is the first item in the iterable.
last: boolean: True when the item is the last item in the iterable.
even: boolean: True when the item has an even index in the iterable.
odd: boolean: True when the item has an odd index in the iterable.

Usage example:

app.component.html
 <ul>
    <li *ngFor="let user of users; index as userIndex; odd as oddUser">        {{user.name}} - {{userIndex}}
        <span *ngIf="oddUser">Odd user</span>    </li>
 </ul>

ngforvariables-odd-example