Angular2 enabled css image path

When I include the style in the component as follows:

@Component({ styleUrls: [ "assets/plugins/test/css/style.css" ], encapsulation: ViewEncapsulation.None }) 

and when the style contains links to images, for example

 .sample { background-image: url(../img/bg.jpg); } 

the browser tries to find bg.jpg on the base url ( http: //localhost/bg.jpg ) instead, it should look for this image in " http: // localhost / assets / plugins / test / img / ".

This happens when Angular2 inserts a style between style tags. Is it possible to insert <link rel="stylesheet" href="..."/> instead of Angular2?

Update 1

Plunker: http://plnkr.co/edit/SHJzVHOyTuLu106r6tpD open the developer console for the browser and search for "bg.jpg"

+8
angular
source share
2 answers

This blog post explains how styles in angular2 override each other http://blog.thoughtram.io/angular/2015/06/25/styling-angular-2-components.html

Citation: โ€œWhere do they end in the DOM? Well, for the same reason as explained earlier, they are written to the beginning of the document. But not only this, when Angular retrieves style resources, it takes a text response, builds the lines and adds them after all inline component styles. "

Inline Styles have the highest priority in Angular2

When working with <link rel="stylesheet" href="..."/> in the header, see this stream CSS file paths are not resolved correctly using Angular ng-view , fixed " / '

<link rel="stylesheet" href="/styles/main.css"/> instead of <link rel="stylesheet" href="styles/main.css"/>

There's a further explanation in this thread. Load external CSS style in Angular 2 Component

Three ways to insert CSS

Perhaps the easiest way is to insert the full path in css

 .sample { background-image: url(/assets/plugins/test/img/bg.jpg); } 

instead

 .sample { background-image: url(../img/bg.jpg); } 
+7
source share

You should load / import the data in the css file according to the base path of your application (you can add <base href="YOUR_APP_DIRECTORY_PATH" /> as the first child of the index.html header for consistency), like this

 body{ background:url(img/img.jpg); } Your Directory Structure should be like this ../ ../ YOUR_APP_DIRECTORY/ img/ Your Images 
+1
source share

All Articles