I've got some CSS rules in my Angular 2 app that would be common across various components. Obviously I don't want to copy&paste them into each component's styles. I currently have 2 ideas:
head
section.@Component
decorator for each component, e.g.
styleUrls: [ './myComponentStyle.css', '../common/common.css']
First approach look not-so-angular-ish to me, but at the same it's sure to work and simple to implement.
Second one requires some work to be done with each component, but allows more control about what styles are being used by one. It also lets me to organize my common styles into smaller stylesheets and use only ones that are needed.
Do you favor any of those solutions or is there a third, better one? :)
1. This solutions is good, but it's more suitable for any common styles, which should be available for all components. For example, styles for css grids. To make it more angularish you could set encapsulation for you app component to none:
`@Component({
selector: 'my-app',
template: ` `,
styleUrls: ["shared.style.css"],
encapsulation: ViewEncapsulation.None
}) export class App {}`
Demo could be found here (plunker)
Note: Styles, included by this ways (just adding style tag, or with non encapsulation) will affect all elements on your pages. Sometimes it is want we really want (agreement to use any css framework for hole project). But if just want to share styles between few component - it would be probably not the best way.
Summary:
(+) easy to use
(-) no encapsulation
2. I like this solution, because it is very understandable and has predictable behavior. But there is one problem with it:
It will add style tag with your shared styles every time you use it. It could be a problem if you have big style file, or many element which are using it.
@Component({
selector: 'first',
template: `<h2> <ng-content> </ng-content> </h2>`,
styleUrls: ["shared.style.css"]
})
export class FirstComponent {}
Demo could be found here (plunker)
Summary:
(+) easy to use
(+) encapsulation
(-) duplicates styles for every usage
3. There is one more option you could use. Just create one more component which will provide shared styles for it's children.
` <styles-container>
<first> first comp </first>
</styles-container>
<styles-container>
<second> second comp </second>
</styles-container>`
In those case you will have to use /deep/ in your styles to make style available for child components:
:host /deep/ h2 {
color: red;
}
I also worth to be mentioned not to forget use :host to make styles available only for child elements. If you omit it you will get one more global style.
Demo could be found here (plunker)
Summary:
(-) you have to create container and it in templates
(+) encapsulation
(+) no duplicated styles
Notes: Encapsulation of styles is really cool feature. But you also should remember that there no way to limit your deep styles. So if you applied deep styles, it would available absolutely to all children, so use it careful too.