How to use ngStyle for background url in Angular 4

The correct answer is [style.background-image]="'url(' + article.uri + ')'"

but if you are using ngFor for carousel, make sure you have added class 'active' properly.

This code will NOT working:

    <div class="carousel-item active"
        *ngFor="let article of arr;"
        [style.background-image]="'url(' + article.uri + ')'"></div>

You should use 'active' class for first item only!

    <div class="carousel-item" 
        *ngFor="let article of arr; let i = index;"
        [ngClass]="{'active': i === 0}"
        [style.background-image]="'url(' + article.uri + ')'"></div>

background-url is incorrect CSS, use background or background-image instead.

Here is an example of correct syntax:

<div [ngStyle]="{'background': '#fff url(' + article.uri + ') no-repeat 0 0'}"></div>

Your full example would look like this:

<li *ngFor="let article of arr; let i=index;" >
   <div *ngIf="i == 0" 
         class="w3l_banner_nav_right_banner" 
         [ngStyle]="{'background': '#fff url(' + article.uri + ') no-repeat 0 0'}" >
     <h3> Make your <span>food</span> with Spicy. </h3>
            <div class="more">
                <a href="products.html" class="button--saqui button--round-l button--text-thick" data-text="Shop now">Shop now1</a>
            </div>
    </div>
</li>

If you're getting your background image from a remote source or a user input you will need to have angular sanitize the url. In your component you will want to add the following bits of code...

import { DomSanitizer } from '@angular/platform-browser';

export class YourComponent {
  constructor(private _sanitizer: DomSanitizer) { }

  public sanitizeImage(image: string) {
    return this._sanitizer.bypassSecurityTrustStyle(`url(${image})`);
  }
}

Try setting your HTML to this...

<li *ngFor="let article of arr;let i=index;">
   <div  *ngIf="i == 0" class="w3l_banner_nav_right_banner" [style.background-image]="sanitizeImage(article.uri)">
     <h3>Make your <span>food</span> with Spicy.</h3>
            <div class="more">
                <a href="products.html" class="button--saqui button--round-l button--text-thick" data-text="Shop now">Shop now1</a>
            </div>
    </div>
</li>

And apply the no-repeat 0px 0px; in some class you attach to the div.

Tags:

Image

Angular