by Sai gowtham

How to set a background image in Angular

How to set a background image in Angular

In this tutorial, we are going to learn about how to set a background image in angular using inline styles and external CSS.

Setting image using inline styles

Example:

<div [ngStyle]="{backgroundImage:'url(./images/rose.png)'}" >    <h1>Rose image</h1>
</div>

In the above code, we have used the angular ngStyle attribute directive to set a background-image to the div element.

Don’t forget to wrap the url() function with single quotes, otherwise angular treated it as a property.

Setting image using external CSS

Example:

app.component.html
<div class="container">
    <h1>Rose image</h1>
</div>
app.component.css
.container{
    background-image: url(./images/rose.png);
}

In the above code first, we have added a container class to the div element, inside the CSS file we set a background image to the container class using background-image property.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course