Angular 2 Load CSS Background Image from Data Folder

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

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)

To demonstrate the purpose, if I change the background image to the following, I get a completely 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 upload this image?

+15
source share
4 answers

try

background-image: url('../../assets/home-page-img/header-bg.jpg');
+34
source

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

CSS

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

HTML

<img src="assets/img/ic-logoembajador-horizontal.svg" alt="logoEmbajador">
+23
source

:

background-image: url('./../assets/home-page-img/header-bg.jpg');
+1

background-image: url(/assets/images/foo.png), i18n + base-href, - .

:

background-image: url(~src/assets/images/foo.png).

:

<img src="assets/images/foo.jpg" />
0

Source: https://habr.com/ru/post/1015748/


All Articles