*ngFor in angular

*ngFor is built-in directive in angular which is used to iterate over items in array or object. ngFor is a structural directive that means it will change only HTML layout in a way you want to show it.

How to use it?

Example of ngFor for array:

In this example we will learn how to iterate item in array.

Create array of users in any component and use *ngFor in HTML to iterate over items.
See following code to learn how to implement it.

Put following code in app.component.ts file.

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  users;

  ngOnInit() {
    this.users = ['John', 'Jane', 'Oliver', 'Bruce'];
  }
}

Put following code in app.component.html file.

<div style="text-align:center">
  <h1>
    *ngFor in angular
  </h1>
</div>
<div>
  <h3>Users</h3>
  <div *ngFor="let user of users">
    <p>{{user}}</p>
  </div>
</div>

Output:

Example of ngFor for object:

In this example we will learn how to iterate item in object.

Create object of users in any component and use *ngFor in HTML to iterate over items.
See following code to learn how to implement it.

Put following code in app.component.ts file.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  users;

  ngOnInit() {
    this.users = {
      1: 'John',
      2: 'Jane',
      3: 'Oliver',
      4: 'Bruce'
    };
  }
}

Put following code in app.component.html file.

<div style="text-align:center">
  <h1>
    *ngFor in angular
  </h1>
</div>
<div>
  <h3>Users</h3>
  <div *ngFor="let user of users | keyvalue">
    <p>{{user.value}}</p>
  </div>
</div>

I have used keyvalue pipe that transforms Object or Map into an array of key value pairs.

Output:

From this article, you learned how to use *ngFor for iterate over items in array or object.

See Also:

Components in angular
Services in angular
template vs templateUrl

Leave a Reply

Your email address will not be published. Required fields are marked *