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.
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
orstyleUrls
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; }']
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) :
Put the specific styles (as few as they are) in an other style sheet and do
styleUrls:["stylesheet1","stylesheet2"]
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.
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.
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