coder_16
coder_16

Reputation: 5

How to parse Json Object in Angular?

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>

Upvotes: 0

Views: 71

Answers (3)

Danielle
Danielle

Reputation: 1486

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)

Upvotes: 0

Passionate Coder
Passionate Coder

Reputation: 7294

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>

Upvotes: 0

Prashant Singh
Prashant Singh

Reputation: 663

Change it to.

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

Upvotes: 2

Related Questions