21

I have problem with background image url. i have array have images url how can I use it in background image url

<div class="col-lg-3 col-md-3 col-sm-6" *ngFor="let course of courses"><a>
    </a><div class="box"><a>
        <div class="box-gray aligncenter"  [style.backgroundColor]="course.imageUrl" >
        </div>
        </a><div class="box-bottom"><a >
            </a><a >{{course.name}}</a>
        </div>
    </div>
</div>
LLL
  • 3,566
  • 2
  • 25
  • 44
eslam masoud
  • 413
  • 1
  • 3
  • 10

4 Answers4

64

Refer to this one Angular2 dynamic background images

// inappropriate style.backgroundColor 
[style.backgroundColor]="course.imageUrl"

// style.backgroundImage
[style.backgroundImage]="'url('+ course.imageUrl +')'"
Hitmands
  • 13,491
  • 4
  • 34
  • 69
16

thank you for your answers, the correct code is

[ngStyle]="{'background-image':'url(' + course.imageUrl + ')'}">
eslam masoud
  • 413
  • 1
  • 3
  • 10
11

You should use background instead of backgroundColor

[style.background]="'url('+course.imageUrl+')'"
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • 1
    Nice i dont know why but if i use *style.backgroundImage* i does not update after the first value change but *background* it works fine jsut have to sanitize the url first – Jeffrey Nicholson Carré Aug 19 '18 at 21:21
4

you can do it by adding url path in a single variable. for example

bgImageVariable="www.domain.com/path/img.jpg";

and

second way
[ngStyle]="{'background-image': 'url(' + bgImageVariable + ')'}"
Coder Girl
  • 175
  • 1
  • 7