Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping CSS out of JS in Angular 2/Angular-CLI

By default, Angular 2 compiles the CSS into JavaScript, especially when using WebPack as in Angular-CLI. I would rather this not happen for a couple of reasons.

The first reason is that when I'm developing, I find it really helps to be able to see in the developer tools exactly what style sheet a specific style rule was coming from and what line number it was on. The second reason is that I think compiling CSS into the code kind of misses the point of good CSS, which is that you can apply a different style sheet and have an entirely different look and feel with the same markup.

Is there a flag somewhere that I can set to leave the CSS in .css files, where IMO it belongs?

like image 584
Amy Blankenship Avatar asked Dec 11 '16 19:12

Amy Blankenship


1 Answers

This is the whole point of encapsulated components.

A component should have it's own styles encapsulated with it so it can be shipped with the styles.

Imagine you want to publish one of your components to be used by others, shouldn't it have its own styles with it ?

That means Angular needs a way to link those css to the component , thus seperates them into chunks and injects them into head tag.

To solve your problem though , you have couple of options :

1- Not using the Emulated Encapsulation :

Components by default have a property called encapsulation which is set to Emulated , you need to change it to None:

@Component({
   encapsulation:ViewEncapsulation.None
})

Then , you can put all you css in the head tag your self like you'd do with a normal html page.

2- If the problem is theme ing , you can make your component themeable .

You can have a theme attribute for your component and then based on that change the styleing :

@Component({
   selector:'my-component',
   styles:[
    `
       :host{
          [theme="blue"]{

              change what ever you want : 

              h1{
                color:blue; 
              }
           }

       }
    `
  ]
})

And then , using this component would be like :

  <my-component [attr.theme]='"blue"'></my-component> // would be blue theme
  <my-component></my-component> // would be default
like image 55
Milad Avatar answered Oct 20 '22 05:10

Milad