0

I am getting profileImage object in which sometime data(profileImage.url) is present and sometimes not(null). How can i write turnary operator in ngStyle so that if profileImage.url is present then show it, other wise user.image (in which common image url is present)

this is i tried

<div class="image-avatar"
  [ngStyle]="{
      'background-image': 'url(' + user.profileImage && user.profileImage.url ? user.profileImage.url : user.image + ')'
    }">
</div>

and i am getting error Cannot read property 'url' of null

Rafi Henig
  • 5,950
  • 2
  • 16
  • 36
aashu1807
  • 203
  • 3
  • 14
  • Please read https://stackoverflow.com/a/37051581/9880356 – Giannis Sep 08 '20 at 13:17
  • @Giannis i also written in same way... what i did wrong? – aashu1807 Sep 08 '20 at 13:18
  • 1
    nothing really looks wrong here, makes me think the error is actually occurring somewhere else... but you should just be able to write `'url(' + user.profileImage?.url || user.image + ')'` – bryan60 Sep 08 '20 at 13:20
  • @bryan60 only left side is working. but when profileImage is null, then its not working for user.image – aashu1807 Sep 08 '20 at 13:23
  • can't speak to why it's not working. maybe something wrong with that property. can't know without seeing the object – bryan60 Sep 08 '20 at 13:25
  • I agree this looks fine. That said, `&& user.profileImage.url != null ` should work. Even better though, I'd place this in the component typescript as a function. – Austin T French Sep 08 '20 at 14:12

1 Answers1

2

I solved it by

<div class="image-avatar" [ngStyle]="{'background-image': user.profileImage && user.profileImage.url ? 'url('+user.profileImage.url+')' : 'url('+user.image+')'}">
aashu1807
  • 203
  • 3
  • 14