简体   繁体   中英

Background Image is not showing in a [ngStyle] Angular 2

I'm having trouble trying to show a image in a div and I kinda don't understand why, could someone help me with this? I know that the methods work cause i used them in different places but i'm not sure if the format of the div is correct.

<div class="attachment-element" [ngStyle]="{'background-image': 'url(' + isPdf(imgUri) ? 'assets/img/pdf_preview.png' : imgUri + ')'}">

仅使用样式的background属性,如下所示

<div class="attachment-element" [ngStyle]="{'background': 'url(' + isPdf(imgUri) ? 'assets/img/pdf_preview.png' : imgUri + ')'}">

Because of operator precedence , your image URL expression is equivalent to the following:

('url(' + isPdf(imgUri)) ? 'assets/img/pdf_preview.png' : (imgUri + ')')

which results in an incorrect format. See this stackblitz for a demo.


You should put parentheses around the conditional operator to get the appropriate format:

'url(' + (isPdf(imgUri) ? 'assets/img/pdf_preview.png' : imgUri) + ')'

See this stackblitz for a demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM