【发布时间】: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
-
无法说明为什么它不起作用。也许该属性有问题。不看物体就无法知道