Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Angular CLI and unable to use relative image paths in CSS files

Have setup an angular app using the angular CLI and have created a component that has an image in the components directory.

For example:

app/
---/common-components
------/header
---------/header.component.ts
---------/header.component.css
---------/images
--------------/image.png

Within the CSS file I am using the following style:

.image {
    background-url: url('images/image.png');
}

When I run the application it gives me a 304 Not Modified and the image does not show up int he preview. If I use an absolute path '/src/app/common-components/header/images' the file loads properly. However, this is not ideal since I would like the component to be self sufficient.

The response that is given is:

Request URL:http://localhost:4201/images/test-image.jpeg
Request Method:GET
Status Code:304 Not Modified
Remote Address:127.0.0.1:4201

With a blank preview

like image 331
glandrum101 Avatar asked Nov 22 '16 17:11

glandrum101


People also ask

How do I give an image a relative path in CSS?

Use the Relative Path /image/picture to Set the Background Image in CSS. We can use the /image/picture file path format to set the background image in CSS. In such a format, the image is located inside the image folder. The image folder is located at the root of the current web.

What is relative path in CSS?

Answer. A relative path is an address that points to the current directory or project folder. In the example illustrated in this lesson, the relative path is images/mountains. jpg and it assumes we have an images subfolder nested within a project folder.

What is relative path in angular?

So by the use of relative path you are making your links free that are relative to the current URL segment. Your feature area of routing will be the same even if you change the route for the parent. You are just making your link free even if you change the parent route path.


1 Answers

All static asset files/directories need to be listed in the angular-cli.json file.

Adding assets

To add your assets you can either:

  • Put your image file in the default assets folder (which is already listed in the angular-cli.json file.
  • Or add a new directory inside of app/ (e.g. in your case you could use app/images, and then reference that in angular-cli.json)

angular-cli.json:

{
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico",
        "images"
      ]
    }
  ]
}

Referencing files

Like @jali-ai mentioned in the comments background-url should be background-image and you can refer to your asset like this:

.image {
   background-image: url('images/image.png'); 
}

Here is an example of the angular-cli.json file and a reference to an asset

like image 71
adriancarriger Avatar answered Oct 01 '22 01:10

adriancarriger