【问题标题】:How to use ternary operator in ngStyle如何在 ngStyle 中使用三元运算符
【发布时间】:2020-09-08 13:12:21
【问题描述】:

我得到profileImage 对象,其中有时存在数据(profileImage.url),有时不存在(null)。我如何在 ngStyle 中编写转元运算符,以便如果 profileImage.url 存在则显示它,否则 user.image(其中存在公共图像 url)

我试过了

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

我收到错误Cannot read property 'url' of null

【问题讨论】:

  • @Giannis 我也以同样的方式写...我做错了什么?
  • 这里看起来没什么问题,让我觉得错误实际上发生在其他地方......但你应该可以写'url(' + user.profileImage?.url || user.image + ')'
  • @bryan60 只有左侧工作。但是当 profileImage 为空时,它不适用于 user.image
  • 无法说明为什么它不起作用。也许该属性有问题。不看物体就无法知道

标签: angular angular8


【解决方案1】:

我解决了

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

【讨论】:

    猜你喜欢
    • 2022-01-04
    • 2020-05-10
    • 2022-01-04
    • 2020-12-19
    • 2010-12-13
    • 1970-01-01
    • 2015-09-15
    • 2014-12-19
    • 2019-11-08
    相关资源
    最近更新 更多