First of all - The styles
/styleUrls
should only be used for any css rules that directly affect the style of the element from your template.
The reason your external.css doesn't get to applied to your component is because when you load these rules in external.css from styleUrls
or styles
, upon compiling, angular2 will append a unique component identifier like attribution selector to your original selectors.
For example, in your external.css, if there is a rule like div.container { /*some rules*/ }
, it will become div.container[_ngcontent-cds-2] { /*some rules*/ }
. So no matter how hard your try to force your rules become priority rules e.g. add !important
tag, it is not going to work -- all selectors in your external.css have been restricted down one level to attribute selector, only the component element carries the same attribute. This is how angular2 restrict the styles to only current component.
Of course there is always a workaround.
Here is my solution -- I will add a external resource service, for all the js script, it will be using SystemJS
to load either AMD or Globally, for all the css files, it will be using plain javascript to create a <link>
element and append it to <head>
element.
Here is a piece of my code for you consideration:
loadCSS(url) {
// Create link
let link = document.createElement('link');
link.href = url;
link.rel = 'stylesheet';
link.type = 'text/css';
let head = document.getElementsByTagName('head')[0];
let links = head.getElementsByTagName('link');
let style = head.getElementsByTagName('style')[0];
// Check if the same style sheet has been loaded already.
let isLoaded = false;
for (var i = 0; i < links.length; i++) {
var node = links[i];
if (node.href.indexOf(link.href) > -1) {
isLoaded = true;
}
}
if (isLoaded) return;
head.insertBefore(link, style);
}