When I include style into component like this:
@Component({
styleUrls: [
"assets/plugins/test/css/style.css"
],
encapsulation: ViewEncapsulation.None
})
and when style contains references to images, for example
.sample { background-image: url(../img/bg.jpg); }
browser tries to find bg.jpg at base url (http://localhost/bg.jpg) instead of that, it should search for that image in "http://localhost/assets/plugins/test/img/".
That happens when Angular2 inserts style between style
tags. Is it possible to make Angular2 insert <link rel="stylesheet" href="..."/>
instead?
Plunker: http://plnkr.co/edit/SHJzVHOyTuLu106r6tpD open browser developer console and search for "bg.jpg"
The key is to either put it into the "assets" folder or to edit your ". angular-cli. json" file (assets section) to include the location where the image is located. This is also true for other resources that are supposed to be served up, i.e. style sheets.
To show the image preview in Angular, we declared the img HTML tag and bind the src tag to the variable. We will assign the image URL to the src variable using the new FileReader() method.
In this blog is posted how styles in angular2 override each other http://blog.thoughtram.io/angular/2015/06/25/styling-angular-2-components.html
Citation: "Where do those end up in the DOM? Well, for the same reason as explained earlier, they are written into the head of the document. But not only that, when Angular fetches the style resources, it takes the text response, inlines and appends them after all component inline styles."
Template Inline Styles have the highest priority in Angular2
When working with <link rel="stylesheet" href="..."/>
in the header see this thread CSS file paths are not resolving properly with angular ng-view, there has to be pre-fixed a '/'
<link rel="stylesheet" href="/styles/main.css"/>
instead of <link rel="stylesheet" href="styles/main.css"/>
In this thread is additional explanation Load external css style into Angular 2 Component
Three Ways to Insert CSS
Maybe the easiest workaround is to insert the full path in the css
.sample { background-image: url(/assets/plugins/test/img/bg.jpg); }
instead of
.sample { background-image: url(../img/bg.jpg); }
You should load / import data in css file according to the base path of your app (You may add <base href="YOUR_APP_DIRECTORY_PATH" />
as first child of head tag of index.html for consistency) like this
body{
background:url(img/img.jpg);
}
Your Directory Structure should be like this
../
../
YOUR_APP_DIRECTORY/
img/
Your Images
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With