0

I'm trying to output JSON values in HTML using ngFor without specifying the object name to render the value in HTML, is this even possible?

I know that I have to specify the object name to actually render the value like the example below.

Let's say I have this JSON object:

'customerObjs':'Ob1'
'FirstName': 'Name'
'Something': 'Something'

And in HTML, I have to do something like the code below to show the value,

<div *ngFor="let obj of Objects">
   {{ obj.FirstName }}
</div>

However, the idea is to render the value even if you don't know the object name. Because what if the backend guy added a new object of YouDontKnowWhatThisIs then the HTML should still render the value of that YouDontKnowWhatThisIs.

So it's more of dynamically outputting the response with hard coding the object name.

Is this possible? If so can someone show an example?

3
  • Can you provide a plunker to this? You need to provide more info to get some good help. Look at your customerObjs, actually it is a list and not an object. It wont even work because it is an invalid JSON. But, try to use the json pipe like: {{obj | json}} so you will see all object fields. Commented Sep 9, 2016 at 12:56
  • edited my customerObj, use a pipe? Commented Sep 9, 2016 at 13:02
  • each time i diplsy json online is with <pre>{{ Objects | json:true }}</pre> Commented Sep 9, 2016 at 13:10

3 Answers 3

2

You can use a custom pipe that extract the keys and value from an object, so you can use them as you need.

keys.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]});
    }
    return keys;
  }
}

myview.html

<p *ngFor="let object of objects | keys">
  <b>{{object.key}}</b>
  <span>{{object.value}}</span>
</p>

I hope it can help you.

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

Comments

1

If this behavior is only local to one component, you can define a getter in it that lists the properties in your object:

@Component({/*...*/})
export class {
    private obj;

    get props() {
        return obj ? Object.keys(this.obj.prop): []
    }
}

With the following template:

<div *ngFor="let prop in props">
   {{obj[prop]}} 
</div>

1 Comment

This is how I'm doing it now before I read this answer. Will give it an upvote :).
0

If you're just debugging an object, you could do a lot worse than a cheeky JSON.stringify equivalent:

<pre>{{object | json}}</pre>

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.