Change style background image dynamically


#1

I need change the background image dynamically. I’ve already tried:

document.getElementById("component-id");

and:

this.app.getComponent(‘component-id’).style.backgroundImage

nothing works!

thx


#2

Its hard to give a good helping answer without a good code example of what you are working with. Can you provide some more code?


#3

@realino You could try the following:

<div id="component-id" [style.backgroundImage]="'url(' + bgImage + ')'">
    <!-- ... -->
</div>
// page.ts
// ...
    this.bgImage = 'path/to/image.jpg';
// ...

If this doesn’t work in your case then you should provide more code, as @dtaalbers suggested.


#4

This solution not working with beta 7 anymore. I dont know why but this is working:

<div id="component-id" [style.backgroundImage]="'url(www.domain.com/path/img.jpg)'">
    <!-- ... -->
</div>

but this is not:

<div id="component-id" [style.backgroundImage]="'url(www.domain.com/path/'+bgImageVariable+')'">
    <!-- ... -->
</div>

//page.ts
this.bgImageVaribale = "bird.jpg";

It has been working before update beta 7.


#5

I’m guessing you’re banging into recent angular changes regarding sanitization.


#6

Edit: http://stackoverflow.com/questions/37076867/in-rc-1-some-styles-cant-be-added-using-binding-syntax

OK. I think there is no solution in this topic, there is only consulting. Is there any workaround or something else?


#7

This has been working for me with beta 7

[ngStyle]="{'background-image': 'url(' + your url + ')'}"

Dynamic tab icons
#8

Thanks, it worked for me


#9

@dtaalbers thanks, i missed the + sign


#10

thank you! it’s working