Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use both styles and styleUrls in an Angular component?

Tags:

angular

In my Angular 2 component, I'm using styleUrls to import a common stylesheet, but dont want to create a whole new stylesheet for a single rule that I want to add specific to this component.

Can I also define styles? So in my component I'm declaring both styles and styleUrls but it doesn't appear to work.

Just wanted to verify if this is possible or not.

like image 791
Dave Avatar asked Aug 16 '17 21:08

Dave


2 Answers

AFAIK, it's not possible to use both style and styleUrls together. The doc says,

There are several ways to add styles to a component:

  • By setting styles or styleUrls metadata.

But, for your problem, I found something helpful in doc:

If you use module bundlers like Webpack, you can also use the styles attribute to load styles from external files at build time. You could write:

styles: [require('my.component.css')]

Set the styles property, not the styleUrls property. The module bundler loads the CSS strings, not Angular. Angular sees the CSS strings only after the bundler loads them. To Angular, it's as if you wrote the styles array by hand. For information on loading CSS in this manner, refer to the module bundler's documentation.

This way you can add both your common stylesheet and the single rule. For example:

styles: [require('his-common.component.css'), 'h1 { font-weight: normal; }'] 
like image 135
Nehal Avatar answered Oct 09 '22 07:10

Nehal


As it was said before, it's not possible to combine style and stylesheet.

If you don't want to mix up your stylesheets, you have some possibilities (from my head what comes first) :

  1. Put the specific styles (as few as they are) in an other style sheet and do

    styleUrls:["stylesheet1","stylesheet2"]

  2. Use require('style-loader!./../../assets/stylesheet.css') to load external stylesheet via the class component for the specific style as you need and when you need.

  3. Move the common element styles to styles.css next to index.html and "free" styleURLs or style: for the specific styles.

There are maybe some other solutions but those should be a good start.

like image 29
Vega Avatar answered Oct 09 '22 08:10

Vega