Home >Web Front-end >CSS Tutorial >How to Use ngStyle to Dynamically Set Background Images in Angular2?
Using ngStyle to Set Background-Image in Angular2
In Angular2, the ngStyle directive allows you to dynamically add CSS styles to an element based on JavaScript expressions. To set a background image using ngStyle, you can use the following syntax:
<code class="html"><div [ngStyle]="{'background-image': 'url(' + photo + ')'}"></div></code>
In your code, it appears that you missed the single quotes around the URL:
<code class="html"><div [ngStyle]="{'background-image': url(' + photo + ')}"></div></code>
To fix this, simply add the missing quotes:
<code class="html"><div [ngStyle]="{'background-image': 'url(' + photo + ')'}"></div></code>
With this change, the ngStyle directive will correctly apply the provided URL as the background image for the div element.
The above is the detailed content of How to Use ngStyle to Dynamically Set Background Images in Angular2?. For more information, please follow other related articles on the PHP Chinese website!