Search code examples
angulartypescriptangular6

parse json content of for key before use in angular 6 template


I'm using Angular 6.

I have an array object in the component file.

items: Array<ItemData>;

ItemData interface has following content

export interface FavouriteProductData {
  id: number;
  type: string;
  content: string;
}

and content contains data in json_encoded format

'{"name":"Jonathan Suh","gender":"male"}';

In the template, I'm looping over items and want to print name field of the content.

<tr *ngFor="let i in items; id = index;">
  <td> {{ i.type }} </td>
  <td> {{ i.content.name }} </td>
</tr>

But since content is json_encoded. I'm not able to print its contents in the template.

How can I parse JSON content in the template and save parsed content in a new variable?

I tried with creating a method in the component

jsonDecode(item) {
  return JSON.parse(item.content);
}

and use in the template like

<tr *ngFor="let i in items; id = index; p = jsonDecode(i)">
  <td> {{ i.type }} </td>
  <td> {{ p.name }} </td>
</tr>

But this is not working.


Solution

  • Your first approach working fine here sample in Stackblitz

    I have done slight changes in array varable declaration.

    Component:

    items : any =[];
    name = 'Angular';
    constructor(){
       this.items = [{id :'1', type :'spec' , content : '{"name":"Jonathan Suh","gender":"male"}'}];
    }
    
    extractNameFromJson(obj){
      obj = JSON.parse(obj);
      return obj.name;
    }
    

    HTML:

    <tr *ngFor="let i of items;">
       <td> {{ i.type }} </td> 
       <td> {{ extractNameFromJson(i.content) }} </td>
    </tr>
    

    Its working as expected try this.