Home > Back-end >  How to parse Json Object in Angular?
How to parse Json Object in Angular?

Time:08-27

I am working with some JSON and want to display the menu in angular only if the image is not null, example JSON is as follows, so if image is null don't show the component, any idea how to loop through this JSON in HTML, I am working on Angular.

Json:

users = [
 {
   user: [
     image: 'user1.png',
     data: {
        name: 'abc'     
        }
   ]
 }
{
   user: [
     image: null,
     data: {
        name: 'xyz'     
        }
   ]
 },
{
   user: [
     image: 'user1.png',
     data: {
        name: 'xyzz'     
        }
   ]
 }
]

Html

<div *ngFor="let user of users">
   // want to show this component only if there is image
   // want to do something like that
   // ngIF="user.image != null" then show but its not working
   <user-image [user]="user"></user-image>
</div>

CodePudding user response:

Change it to.

<div *ngFor="let user of users">
   <user-image *ngIf="user?.image" [user]="user"></user-image>
</div>

CodePudding user response:

your Object is giving error to me so I changed it little bit.

You can try below solution

users = [
    {
      user: {
        image: 'user1.png',
        data: {
           name: 'abc'     
           }
          }
    },
   {
      user: {
        image: null,
        data: {
           name: 'xyz'     
           }
          }
    },
   {
      user: {
        image: 'user1.png',
        data: {
           name: 'xyzz'     
           }
          }
    }
  ]
}


<div *ngFor="let userObj of users">
  <user-image  *ngIf="userObj.user?.image" [user]="userObj.user"></user-image>
</div>

CodePudding user response:

If only when image is different than null, you can do something like

   <user-image *ngIf="user.image != null" [user]="user"></user-image>

Although user-image will be displayed even if the content of image is "" or has any other value than null (true, false, 123, "123", "", etc)

  • Related