user3763577
user3763577

Reputation: 1

Background images won't load dynamically

I'm trying to set the background image of a div dynamically using Angular 6... But for some reason no matter what I do, It seems I can't make the image to render. The images are being served from a local SimpleHTTPServer using python.

HTML:

<a *ngFor="let movie of movies">
    <div [style.background-image]="movie.image">
        {{movie.name}}
    </div>
</a>

Component:

getMovies() : void {
    this.movieService.getMovies().subscribe(movies => this.movies = movies.map(movie => {
        movie.image = this.sanitizer.bypassSecurityTrustStyle(`url(${movie.image})`);
        return movie;
    }));
}

I've tried also using the sanitizer with no success... And i'm not getting any errors.

Upvotes: 0

Views: 117

Answers (2)

user3763577
user3763577

Reputation: 1

Make sure the url is URI Encoded. In JS: encodeURI(url)

Upvotes: 0

Sagar Rana
Sagar Rana

Reputation: 568

You can use like this:

<a *ngFor="let movie of movies">
    <div [ngStyle]="{'background-image': 'url(' + movie.image + ')'}"> {{movie.name}}</div>
</a>

or

 [style.backgroundImage]="'url('+ movie.image +')'"

Updated: You should also mention height and width in div as mentioned by user184994 in comment section like this:

<div [ngStyle]="{backgroundImage: 'url(' + movie.image + ')', width: '200px', height: '150px'}"></div>

Upvotes: 1

Related Questions