Search code examples
htmlangulartypescriptng-style

NgStyle with dynamic content proper syntax angular 4/2


I am using NgStyle to dynamically set the background image of a container in angular 4.

This site: Says the proper syntax is the following

[ngStyle]="{'background-image': venueobject.groupphoto[0]}">

or

[ngStyle]="{'background-image': 'venueobject.groupphoto[0]'}">

I also saw turning the whole thing into a string:

[ngStyle]="'background-image': 'url(' + 'venueobject.groupphoto[0]'+ ')'">

and

[ngStyle]="'background-image: url(' + venueobject.groupphoto[0] + ')'">

but I keep not getting it. The page is rendering so my html is not broken, but the image is not showing.

This is currently not yay and I am trying to make it yay.

Please help me make it yay

Hugs and kisses


Solution

  • You can try the following:

    In your ts file:

    import { DomSanitizer } from '@angular/platform-browser';
    
    constructor(private sanitizer: DomSanitizer) { }
    
    getBackgroundImg() {
        // replace the path to your image here
        const img = 'assets/img/wall.png';
        const style = `background-image: url(${img})`;
        // this is to bypass this warning 'WARNING: sanitizing unsafe style value background-image: url(assets/img/wall.png) (see http://g.co/ng/security#xss)'
        return this.sanitizer.bypassSecurityTrustStyle(style);
    }
    

    In your html file:

    <div [style]="getBackgroundImg()"></div>
    

    You will also need to set the width and height of the div to see the image.