How to show property of json string using interpolation in Angular 6+?

Viewed 1935

Let's say we have a list of JSON object like this one:

data = {
   id: 1,
   someObjAsString: '{"p1":"a", "p2": "b"}',
   ...
   ... other properties
}

Using *ngFor I want to display p2 from someObjAsString:

<div *ngFor="let data of dataList">
{{data.someObjAsString.p2}} <!-- What should I do here to display p2 property of someObjAsString-->
</div

JSON.parse() is definitly not working

Any help would be appreciated.

1 Answers

As someObjAsString is object, then you can use keyvalue pipe:

<div *ngFor="let item of dataList.someObjAsString | keyvalue">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>

Usually ngFor is used to iterate through arrays.

UPDATE:

As your object is stored as string, then we can use json.parse() to construct the JavaScript value or object:

data = {
  id: 1,
  someObjAsString: '{"p1":"a", "p2": "b"}',
  anotherObj: '{"p1":"a", "p2": "b"}'
};


ngOnInit(){
    for (const key in this.data) {
        if (this.data.hasOwnProperty(key)) {
             this.data[key] = JSON.parse(this.data[key]);
        }
     }
     console.log(this.data);
}

And HTML:

<div *ngFor="let item of data | keyvalue">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value | json}}</b>

    <div *ngFor="let someObj of item | keyvalue">
        someObj Key: <b>{{someObj.key}}</b> 
          and someObjValue: <b>{{someObj.value | json}}</b>
    </div>
</div>

A complete workstackblitz example can be see here.

Related