Home  >  Forum  >  Angular
Post New Query

Angular 2 Load Background Image using NgStyle and Style Binding


joined on
August 11,2014
Asked on November 25,2016

How to load background image using NgStyle and style binding in Angular 2 ?

joined on
October 10,2013
Replied on November 25,2016

In angular 2 we can use background-image property as follows.

1. Using style binding

<div [style.background-image] = "isBackgroundRed ? 'url(\'images/red.gif\')' : 'url(\'images/green.gif\')'">
Style Binding Example
</div>  

2. Using NgStyle

Create a method in component.

getMyStyles() {
    let myStyles = {
       'background-image': !this.isBackgroundRed ? 'url(\'images/red.gif\')' : 'url(\'images/green.gif\')',
       'color': this.colorFlag ? 'black' : 'yellow'
    };
    return myStyles;
}  

Call the method using ngStyle

<div [ngStyle]="getMyStyles()">
NgStyle Example
</div>  

We need to use backslash (\) here otherwise it will throw error.

Find the link

Write Answer




Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us