0

I am trying to print JSON array in HTML using ngFor

TS :

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-ng-for',
  templateUrl: './ng-for.component.html',
  styleUrls: ['./ng-for.component.scss']
})
export class NgForComponent implements OnInit {
  public colors = ["red","blue","green","black","yellow", "pink"]
  public count = [1,2,3,4,5, 6]
  public item = [
    {"one" : 1},
    {"two" : 2}
  ]
  constructor() { }
  ngOnInit() {
  }
}

HTML :

<h1> NG For </h1>

<div *ngFor="let color of colors">
    <p>{{color}}</p>
</div>
<div *ngFor="let c of count">
    <p>{{c}}</p>
</div>

<div *ngFor="let val of item ">
    <p>{{val | json}}</p>
</div>

Here is the output :

enter image description here

But I want to pring Key and Value seperately like this :

KEY : one, Value : 1
KEY : two, Value : 2

What changes should I do?

Ashish
  • 479
  • 3
  • 7
  • 18
  • Does this answer your question? [Iterate over object in Angular](https://stackoverflow.com/questions/31490713/iterate-over-object-in-angular) – Tal Ohana Sep 13 '20 at 18:54
  • Does this answer your question? [angular \*ngFor from json](https://stackoverflow.com/questions/63857078/angular-ngfor-from-json) –  Sep 14 '20 at 06:47

1 Answers1

4

You can use the following HTML for this (Working Demo):

<div *ngFor="let item of items">
  <p *ngFor="let val of item | keyvalue">
    {{'KEY: ' + val.key + ', VALUE: ' + val.value }}
  </p>
</div>

It's using the keyvalue pipe instead of the json pipe.

And if you want a single ngFor loop you can change the data structure to this:

items = {
  "one" : 1,
  "two" : 2
}

And your HTML template to this:

<p *ngFor="let item of items | keyvalue">
  {{'KEY: '+item.key + ', VALUE: ' + item.value }}
</p>
Asaf
  • 1,446
  • 9
  • 17