2

I am new to angular. I am trying to display Json object in component. I am using keyvalue pipe with *ngFor to achieve this.

My Json Object

{
  "categories": [
    {
      "categories": {
        "id": 1,
        "name": "Delivery"
      }
    },
    {
      "categories": {
        "id": 2,
        "name": "Dine-out"
      }
    },
    {
      "categories": {
        "id": 3,
        "name": "Nightlife"
      }
    },
    {
      "categories": {
        "id": 4,
        "name": "Catching-up"
      }
    },
    {
      "categories": {
        "id": 5,
        "name": "Takeaway"
      }
    }
  ]
}

My Component HTML:

<div *ngFor="let obcategories of users | keyvalue">
    <div *ngFor="let obcategory of obcategories.value | keyvalue">
        <div *ngFor="let nestedobcategory of obcategory.value | keyvalue">
            {{nestedobcategory.value}}
        </div>
    </div>
</div>

It is displaying all both id value and name value. I want to display only name value.

Any help is much appreciated.

3
  • Your JSON is not matching with *ngFor keys, values. Commented Dec 26, 2019 at 9:54
  • Try directly with {{obcategory.name}} and remove the 3rd nested *ngFor. Commented Dec 26, 2019 at 9:56
  • 1
    hi, your code is good enough you just use {{nestedobcategory.value.name}} instead of {{nestedobcategory.value}} Commented Dec 26, 2019 at 10:01

3 Answers 3

3

You can use {{nestedobcategory.value.name}} to access the name property:

<div *ngFor="let obcategories of users | keyvalue">
    <div *ngFor="let obcategory of obcategories.value | keyvalue">
        <div *ngFor="let nestedobcategory of obcategory.value | keyvalue">
            {{nestedobcategory.value.name}}
        </div>
    </div>
</div>

Working Demo

Sign up to request clarification or add additional context in comments.

2 Comments

I was breaking my head till now. Thanks a lot your solution works like a charm.
You are welcome. Just a tip, if you see something is not printing, try with {{nestedobcategory.value | json}} you will get a clear picture of what is happening. And kindly upvote if you don't mind :)
2

Change:

{{ nestedobcategory.value }}

To:

{{ nestedobcategory.value.name }}

Code after changes:

<div *ngFor="let nestedobcategory of obcategory.value | keyvalue">
      {{ nestedobcategory.value.name }}
</div>

Working Demo

Comments

1

A minor change would be:

nestedobcategory.value => nestedobcategory.value.name

IMP : In such cases use JsonPipe just to check what object you getting. If you use

{{ nestedobcategory.value | json }}

It will display your objects in the JSON Structure (Key/Value pair) and then you can access values that you want to display on the HTML.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.