Change style background image dynamically

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 Likes

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 + ')'">
    <!-- ... -->
</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.

17 Likes

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.

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

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?

This has been working for me with beta 7

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

Thanks, it worked for me

@dtaalbers thanks, i missed the + sign

1 Like

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": [
    -1,
    -40,
    -1,
    -32,
    0,
    16,
    74,
   . . .

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

image.component.ts

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

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

    ngOnInit(): void {
        this.imageService.getData()
            .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);
        });
 
    }
}

image.service.ts

    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 this.http.post('http://myserviceurl/findImageByImageName', JSON.stringify ({ 'java.lang.String':'MY_IMAGE_NAME' }), { headers: headers});
}

image.component.html

<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.