0

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>
3
  • *ngIf='user.image' check with this. Commented Aug 26, 2022 at 16:26
  • users is not JSON, users is a JavaScript object. Commented Aug 26, 2022 at 16:41
  • That is not json, its is a JS object Commented Aug 26, 2022 at 19:59

3 Answers 3

2

Change it to.

<div *ngFor="let user of users">
   <user-image *ngIf="user?.image" [user]="user"></user-image>
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.