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,199
  • 2
  • 22
  • 39
eslam masoud
  • 413
  • 1
  • 3
  • 9

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
  • 12,577
  • 3
  • 30
  • 62
16

thank you for your answers, the correct code is

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

You should use background instead of backgroundColor

[style.background]="'url('+course.imageUrl+')'"
Pankaj Parkar
  • 130,886
  • 22
  • 223
  • 289
  • 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
  • 165
  • 1
  • 7