nCore
nCore

Reputation: 2087

angular2 output object value in html without specifying object name

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?

Upvotes: 0

Views: 671

Answers (3)

entozoon
entozoon

Reputation: 350

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

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

Upvotes: 0

Frank Bessou
Frank Bessou

Reputation: 652

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>

Upvotes: 1

Bruno Jo&#227;o
Bruno Jo&#227;o

Reputation: 5525

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.

Upvotes: 2

Related Questions