How to put background image in angular 2

5.3k views Asked by At

I tried putting background url for my image

 <div  [ngStyle]="{'background-image': 'url(' + https://s3-us-west-2.amazonaws.com/mysite/l/{{event.photo}} + ')'}"></div>

I am getting this error

Parser Error: Got interpolation ({{}}) where expression was expected 

Can anyone please hepl me.Thanks.

5

There are 5 answers

1
Alexander_F On

I would suggest to build the styleString in the controller. The just use a simple variable in your code. Much cleaner this way.

0
Sudharsan Sun On

I would like you verify above link to get better idea on background images

Angular2 dynamic background images

Attribute property binding for background-image url in Angular 2

Thank you

0
codeExcalibur On

Try this instead:

<div  [ngStyle]="{'background-image': 'url('+'https://s3-us-west-2.amazonaws.com/mysite/l/'+event.photo+')'}"></div>

that works fine as of angular v4 and later

0
Shiladitya On

Yor can't use property binding & interpolation together.

So try using the below code only property binding

<div [ngStyle]="{'background-image': 'url(https://s3-us-west-2.amazonaws.com/mysite/l/' + event.photo + ')'}"></div>

Hope this will help you.

0
Admir On

You can also use [style.background-image]

<div [style.background-image]="'url(https://s3-us-west-2.amazonaws.com/mysite/l/'+ event.photo +')'">