glandrum101
glandrum101

Reputation: 466

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

Upvotes: 18

Views: 30284

Answers (4)

ximage
ximage

Reputation: 513

You can use caret syntax to ignore url processing

background-image: url('^images/objects/loader.png');

Angular CLI just passthrough your url removing Caret

background-image: url('images/objects/loader.png');

Upvotes: 4

ÐerÆndi
ÐerÆndi

Reputation: 139

It seems to be still an issue with angular-CLI and webpack (using 1.0.3).

If you add the asset folder to the angular-cli.json and define the path relatively, the build still fails, not finding the ressources url('someRelativeLink').

I used a work around and put all CSS definitions in:

@Component({
  styles: [...]
})

Instead of a styleUrls file.

After doinig that everything was fine.

Upvotes: 3

jaimin patel
jaimin patel

Reputation: 219

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

Upvotes: -1

adriancarriger
adriancarriger

Reputation: 3000

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

Upvotes: 31

Related Questions