*ngFor in angular

*ngFor is a 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 items in an array.

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

Put the following code in the 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 the following code in the 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 items in objects.

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

Put the following code in the 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 the following code in the 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 to iterate over items in an array or object.

See Also:

Components in angular
Services in angular
template vs templateUrl

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments