Categories
Angular Answers

How to iterate object keys using *ngFor in Angular?

Spread the love

Sometimes, we want to iterate object keys using *ngFor in Angular.

In this article, we’ll look at how to iterate object keys using *ngFor in Angular.

How to iterate object keys using *ngFor in Angular?

To iterate object keys using *ngFor in Angular, we can use the keyvalue pipe.

For instance, we write

@Component({
  selector: "keyvalue-pipe",
  template: `<span>
    <p>Object</p>
    <div *ngFor="let item of object | keyvalue">
      {{ item.key }}:{{ item.value }}
    </div>
    <p>Map</p>
    <div *ngFor="let item of map | keyvalue">
      {{ item.key }}:{{ item.value }}
    </div>
  </span>`,
})
export class KeyValuePipeComponent {
  object: { [key: number]: string } = { 2: "foo", 1: "bar" };
  map = new Map([
    [2, "foo"],
    [1, "bar"],
  ]);
}

to add use the keyvalue with *ngFor.

We use it to render entries in objects and maps.

And we get the key from the key property and the value from value.

Conclusion

To iterate object keys using *ngFor in Angular, we can use the keyvalue pipe.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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