Change style background image dynamically

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



nothing works!



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?

@realino You could try the following:

<div id="component-id" [style.backgroundImage]="'url(' + bgImage + ')'">
    <!-- ... -->
// 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.


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

<div id="component-id" [style.backgroundImage]="'url('">
    <!-- ... -->

but this is not:

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

this.bgImageVaribale = "bird.jpg";

It has been working before update beta 7.

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


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

This has been working for me with beta 7

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

Thanks, it worked for me

@dtaalbers thanks, i missed the + sign

thank you! it’s working

Can anyone please help me in similar situation but with canvas background image. It works with <img… />
<img id="myimage" [src]='thumbnail' height='500' width='500' />

but doesn’t work with <canvas … />

<canvas id="canvas5" width="100" height="100" 
   	[ngStyle]="{'background-image':'url(' + thumbnail + ')'}"> </canvas>

Do you get any error? What’s the result you expect and what do you get?

I don’t see any error in browser console.
I do see the REST service is returning json data:

  "bitmapFileName": "MY_IMAGE.JPG",
  "imageName": "MY IMAGE",
  "imageDescription": "My Image Desc",
  "imageData": [
   . . .

Can you please provide some more code so I could understand what you’re trying to do?


export class CreateImageComponent implements OnInit {
    @Input() thumbnail: any;

    constructor(private http: Http, 
        private router: Router,
        private location: Location,
        public setting:SettingsService, 
        private sanitizer: DomSanitizer,
        private imageService: QiImageService
    ) { }

    ngOnInit(): void {
            .subscribe( (baseImage : any) => {
                const img = baseImage._body;
                var imageJson = JSON.parse(img);
                let TYPED_ARRAY = new Uint8Array(imageJson.imageData);
                const STRING_CHAR = String.fromCharCode.apply(null, TYPED_ARRAY);
                let base64String = btoa(STRING_CHAR);
              let objectURL = 'data:image/png;base64,' + base64String;
               this.thumbnail = this.sanitizer.bypassSecurityTrustUrl(objectURL);


    getData(): Observable<any> {
        var headers = new Headers();
        headers.append('Access-Control-Allow-Origin', '*');
        headers.append('Access-Control-Allow-Methods', 'POST');
        headers.append('Access-Control-Allow-Credentials', 'true');
        headers.append("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        headers.append('Content-Type', 'application/json');
        headers.append('Accept', 'application/json');
        const formdata: FormData = new FormData();
        formdata.append('java.lang.String', 'TG7 RR FLOOR');
      //  formdata.append('Access-Control-Allow-Origin', 'true');
        return'http://myserviceurl/findImageByImageName', JSON.stringify ({ 'java.lang.String':'MY_IMAGE_NAME' }), { headers: headers});


<canvas id="canvas" width="100" height="100" 
	[style.background]="'url('+ thumbnail +')'"> </canvas>

<canvas id="canvas1" width="100" height="100" 
	[ngStyle]="{background:'url(' + thumbnail + ')'}"> </canvas>
<canvas id="canvas2" width="100" height="100" 
	style="background:url({{thumbnail}})">  </canvas>

<canvas id="canvas3" width="100" height="100" 
   	[ngStyle]="{'background':'url(' + thumbnail + ')'}"> </canvas>
<canvas id="canvas4" width="100" height="100" 
	[style.backgroundImage]="'url('+ thumbnail +')'"> </canvas>
<canvas id="canvas5" width="100" height="100" 
   	[ngStyle]="{'background-image':'url(' + thumbnail + ')'}"> </canvas>

<canvas id="canvas6" width="100" height="100" 
   	[style.background-image]="'url(' + thumbnail + ')'"> </canvas>

<!-- <img id="myimage" [src]='thumbnail' height='500' width='500' /> -->

Okay so what I think this isn’t gonna work if you use sanitization while binding a style. That’s what I understand from the angular docs:

“In specific situations, it might be necessary to disable sanitization, for example if the application genuinely needs to produce a javascript: style link with a dynamic value in it.”

Try to bind your background picture just like this:
this.thumbnail = objectURL;
Beside canvas2 (you’re missing the url part) it should all work well. I’m not sure anyway, tell me if I’m wrong.

At least now I can see a placeholder. But it is a blank.