[Fixed] How to use ngStyle for background url in Angular 4

Issue

I have below html:

  <li>
    <div class="w3l_banner_nav_right_banner1" style="background:url('./assets/images/2.jpg') no-repeat 0px 0px;">
        <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 now</a>
            </div>
    </div>
</li>

Problem:

I want to replace image url /assets/images/2.jpg with dynamic variable like {{ article.uri }}.

I tried with several way from below ref:

Attribute property binding for background-image url in Angular 2

How to add background-image using ngStyle (angular2)?

Tried so far:

<li *ngFor="let article of arr;let i=index;">
   <div  *ngIf="i == 0" class="w3l_banner_nav_right_banner" [ngStyle]="{ 'background-url': 'url('+article.uri+')'} no-repeat 0px 0px;">
     <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>

I am using Angular 4.1.3.

Solution

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>

Leave a Reply

(*) Required, Your email will not be published