41

In the html template I have this style with a dynamic image:

<div style="background: url('/img/{{item.img}}'); width: 200px; height: 150px"></div>

Which works in web browsers and android browser. However background images that are dynamic using "style=" are not showing on iPad.

I could always create dynamic images using the img tag but I'm looking for a style/css solution for iPad.

Pat M
  • 5,768
  • 6
  • 22
  • 32

4 Answers4

100

Use instead

<div [ngStyle]="{background: 'url(/img/' + item.img + ')', width: '200px', height: '150px'"></div>

or

<div [style.background]="'url(/img/' + item.img + ')'"
    [style.width.px]="200" [style.height.px]="150p"></div>

See also In RC.1 some styles can't be added using binding syntax

Community
  • 1
  • 1
Günter Zöchbauer
  • 558,509
  • 191
  • 1,911
  • 1,506
  • 1
    This works until you have an image that name contains brackets: some_image_(7).jpg – wawka Apr 03 '20 at 11:23
  • @wawka might be a browser problem, not an Angular problem https://bugzilla.mozilla.org/show_bug.cgi?id=478139. Thanks for the info anyway. Others might run into that as well. – Günter Zöchbauer Apr 03 '20 at 12:14
  • Nope. The same problem is on Chrome as well, which makes sense. Look how the background looks like `style="url(some_image_(7).jpg)"`. I guess you see where the problem is :) It causes the bracket closes too early. – wawka Apr 06 '20 at 05:05
  • Still not clear why this should be Angular related. Have you tried in plain CSS? Have you tried `style="url('some_image_(7).jpg')"` – Günter Zöchbauer Apr 06 '20 at 05:19
  • This is an issue as you don't bind `style="url('some_image_(7).jpg')"` but `style="url(some_image_(7).jpg)"` (notice that there is no single quoted inside url). – wawka Apr 06 '20 at 05:27
  • Still not clear how this is related to this SO question/answer or Angular. What prevents you from adding the quotes to the string? – Günter Zöchbauer Apr 06 '20 at 05:30
14

You should do that as the +Günter Zöchbauer second part answer generates unwanted supplementary style background-position: initial and background-size: initial on Safari at least.

Note that I only set the background-image style:

<div [style.background-image]="'url(/img/' + item.img + ')'"
 [style.width.px]="200" [style.height.px]="150p"></div>
Stéphane de Luca
  • 11,714
  • 8
  • 50
  • 75
7
<div id="component-id" [style.background-image]="'url(www.domain.com/path/'+bgImageVariable+')'">
    <!-- ... -->
</div>

or

<div id="component-id" [style.background-image]="'url('+bgImageVariable+')'">
    <!-- ... -->
</div>

you can use in second way by adding URL path in a single variable. for example

bgImageVariable="www.domain.com/path/img.jpg";
Yashwardhan Pauranik
  • 5,160
  • 5
  • 37
  • 59
Coder Girl
  • 165
  • 1
  • 7
1

use this and set height and width of div tag as per you need

<div id="component-id" [style.backgroundImage]="'url('+bgImageVariable+')'"></div>
Manoj Rana
  • 2,212
  • 1
  • 22
  • 25