Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Load CSS background-image from assets folder

Tags:

html

css

angular

My folder structure looks like

-myapp     -assets         -home-page-img             -header-bg.jpg     -src         -app         -home-page             -home-page.component.css             -home-page.component.html             -home-page.component.ts 

Inside my home-page.component.css, I have the following

header {     width: 200px;     height: 200px;     background-image: url('/src/assets/home-page-img/header-bg.jpg'); }  My angular-cli.json     "assets": [     "assets",     "favicon.ico" ] 

When I run the code, I get

GET http://localhost:4200/src/assets/home-page-img/header-bg.jpg 404 (Not Found) 

For demonstrating purpose, If I change background-image to the following, I get a whole different error

background-image: url('assets/home-page-img/header-bg.jpg');  ./src/app/home-page/home-page.component.css Module not found: Error: Can't resolve './assets/home-page-img/header-bg.jpg' in '/Users/JohnSmith/Desktop/my-app/src/app/home-page' 

How can I get that image to load?

like image 925
ErnieKev Avatar asked Mar 15 '17 06:03

ErnieKev


2 Answers

I use it. Always starting with "/assets/" in CSS and HTML "assets/". And I have no problems. Angular recognizes it.

CSS

.descriptionModal{     background-image: url("/assets/img/bg-compra.svg"); } 

HTML

<img src="assets/img/ic-logoembajador-horizontal.svg" alt="logoEmbajador"> 
like image 119
Samuel Ivan Avatar answered Sep 18 '22 13:09

Samuel Ivan


try

background-image: url('../../assets/home-page-img/header-bg.jpg'); 
like image 24
Thyagarajan C Avatar answered Sep 21 '22 13:09

Thyagarajan C