Angular 2 Load Background Image using NgStyle and Style Binding

Asked on November 25, 2016
How to load background image using NgStyle and style binding
in Angular 2 ?

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 NgStyleCreate 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