Shared styles across components in an Angular 2 app - css

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:
Place common CSS rules in a static CSS file and include it using a link in my index.html's head section.
Place my common CSS rules in one or more files and include them in #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.

There are 3 ways to use styling in angular2 app (link).
You have mentioned two of those that allows you to reuse styles.
My personal opinion is that for any large application its preferable to go with #2 mainly due to the view encapsulation provided by angular.
#1 can be used for the really very generic styles that are common to all parts of your application. But if you will take into account that the root in your SPA will be angular component anyway - there is no real need to go with another approach of linking styles than #2.
Moreover by working with css in two different ways you will have to remember this (and handle with some extra code) when for example bundling your app and using tools like gulp-inline-ng2-template

For future readers, I think this solution is best.
Let's assume you have 2 components(products and customers), and have common styles to be shared.
1.Create one more component
//customer-products-styles.component.ts
#Component({
selector: "app-customer-products-styles",
template: "",
styleUrls: ["./customer-products-styles.component.scss"],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class CustomerProductsStylesComponent {}
//customer-products-styles.component.scss
app-products,
app-customers {
p {
color: coral;
}
}
2.Use it like so
<!-- Customers Component (app-customers) -->
<app-customer-products-styles></app-customer-products-styles>
<p>
customers works!
</p>
<!-- Products Component (app-products) -->
<app-customer-products-styles></app-customer-products-styles>
<p>
products works!
</p>
Benefits
It is lazy-loaded, loads when module chunk is downloaded, initial
main.js is reduced
Adding component selectors (app-customers and
app-products) as a parent for styles make it component scope
No duplicate styles and only load once in the browser, whatever the component request it first
Some Additional points
Set encapsulation to none, but add component selector as parent in the style
I also changed default changeDetection to OnPush, there is no need but to be safe
Working Stackblitz

Related

When and why should we use View Encapsulation in angular

When working in angular is there a particular rule or guideline that should be used in deciding when to use and why to use View Encapsulation?
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
encapsulation: ViewEncapsulation.None /*What is the use of this line*/
})
Can someone please explain in simple ways?
Codecraft.TV has an amazing article on ViewEncapsulation that you can refer to get a better understanding.
To just summarize it:
ViewEncapsulation.Emulated: Angular changes our generic css class selector to one that target just a single component type by using automatically generated attributes.
Any styles we define on a component don’t leak out to the rest of the application but with ViewEncapsulation.Emulated our component still inherits global styles.
ViewEncapsulation.Native: If we want Angular to use the shadow DOM we can set the encapsulation parameter to use ViewEncapsulation.Native
With ViewEncapsulation.Native styles we set on a component do not leak outside of the components scope.
This is great if we are defining a 3rd party component which we want people to use in isolation. We can describe the look for our component using css styles without any fear that our styles are going to leak out and affect the rest of the application.
However with ViewEncapsulation.Native our component is also isolated from the global styles we’ve defined for our application. So we don’t inherit the global styles and have to define all the required styles on our component decorator.
Finally ViewEncapsulation.Native requires a feature called the shadow DOM which is not supported by all browsers.
ViewEncapsulation.None: If we don’t want to have any encapsulation at all, we can use ViewEncapsulation.None.
If we don't encapsulate anything, the style we defined in the component will leak out and started affecting the other components.
Some other resources that you might want to have a look into:
VIEW ENCAPSULATION IN ANGULAR - By Thoughtram
View Encapsulation by Rangle.IO
Scoping Your Styles in Angular With ViewEncapsulationView
Diff between ViewEncapsulation.Native, ViewEncapsulation.None and ViewEncapsulation.Emulated
Let's take one example where we have one parent and one child component with their own html, ts, css files.
Suppose in parent component's html you referenced child component like below-
parent.component.html -> <app-child> </app-child>
Now, if you create and add any similar styles like parent.component.css file in child.component.css (let's take <p> tag as an example) then those will get added to each component seperately even if all angular component's html gets rendered on single page.
So now you will have seperate styles for <p> in child component.(Behind the scene angular adds one random_atttr to each component and then to all elements inside that component)
This behaviour of angular, comes in view encapsulation. Used by angular like shadow DOM techonlogy which is not supported by all broswers but angular does it like this.
ViewEncapsulation has 3 options -
encapsulation: ViewEncapsulation.None,
ViewEncapsulation.Emulated, (-- this is default)
ViewEncapsulation.Native (-- only applies to browsers with shadow DOM technology)<br>

How to prevent global css selectors to interfere with isolated components in Angular (6)?

Even if your component stylesheet will be applied in isolation to its component only (e.g. while using the default ViewEncapsulation.Emulated) the class names you will use on your template will still clash with any existent global styling, so you cannot really use more than one single class namespace.
This can lead to always prefixing class names, which in turn can result in very long, weird name groups.
Is there any best practice out there to keep your class names brief and clean (ideally 1-word) without any risk of clashing with any global styling that might be in place?
Real use case example: I can't use class="row" while styling a component-wide custom logical row if I am using bootstrap.
Look at this StackBlitz. I want the header of my a component to be fixed-width and bordered only, but it ends up to also have a red background because of global styling.
Yes. I can use a different word, but I should always be aware of the entire word set that is currently used by global styling, not to mention that I don't know whether more global styles will be added in the future, especially in large applications.
Changing your view encapsulation to native will make Angular use native shadow DOM and avoid the clash of the global style
#Component({
selector: 'app-a',
templateUrl: './a.component.html',
styleUrls: ['./a.component.css'],
encapsulation: ViewEncapsulation.Native
})

is it possible to write CSS for all Angular "hosts" or do we have to select each host individually

The Angular documentation for :host does not mention that we can style all host elements at once. I have added this CSS at a “global” level:
:host {
width: 100%;
}
but there was no effect. However, this works fine in the CSS at the component level:
:host(app-search) {
width: 100%;
}
where app-search is a component, app-search.component.ts.
Is is possible to write a :host selector for all components or must this be declared multiple times at the component level?
By its very definition (or specification), :host can never be used at a global level. It is created to use from component level and to select the parent component (which is called shadow host) from the children (which is called shadow tree).
For more clarification, Angular's :host selector is a special selectors from the world of shadow DOM style scoping (described in the CSS Scoping Module Level 1 page on the W3C site).
The angular documentation clearly specifies that you should use this selector to select the parent component from within the child component. But it may seem unclear to you if you don't have any idea how shadow tree works. see the documentation.
If you need to style any component from a global stylesheet, there is a style.css file automatically added at a global scope in Angular. Just put your CSS in that file and you can find it available globally in all components.
Component level CSS files make your CSS modular. This is a great feature because:
You can use the CSS class names and selectors that make the most
sense in the context of each component.
Class names and selectors are local to the component and don't collide with classes and selectors
used elsewhere in the application.
Changes to styles elsewhere in the
application don't affect the component's styles.
You can co-locate
the CSS code of each component with the TypeScript and HTML code of
the component, which leads to a neat and tidy project structure.
You
can change or remove component CSS code without searching through the
whole application to find where else the code is used.
Although it is configurable, I strongly recommend not to use ViewEncapsulation.None. It will make kill all your CSS modularity which you can avail easily using global CSS files without affecting the scoping restriction.
In your app-search.component.ts file, you could set:
encapsulation: ViewEncapsulation.None
like this
#Component({
templateUrl: 'app-search.component.html',
styleUrls: ['app-search.component.css'],
encapsulation: ViewEncapsulation.None
})
This prevents you from having to rewrite styles and enables styles on a global level.
You could also try applying the styles directly into the index.html file. These styles will also be global, preventing you from rewriting styles at the component level.

How to style a AngularDart component using eventually multiple CSS files

I was wondering what is the best way to style AngularDart components? I'd like to be able to split base styles into a separate CSS file and then just include it somehow (maybe #import, if angular dart supports it) in my component.
Standard NgComponent allows me to add only once CSS file, as in the following example:
#NgComponent(
selector: 'rating',
templateUrl: 'packages/angular_dart_demo/rating/rating_component.html',
cssUrl: 'packages/angular_dart_demo/rating/rating_component.css',
publishAs: 'ctrl',
map: const {
'max-rating': '#maxRating',
'rating': '<=>rating'
})
What if my CSS is somehow split across multiple files, how do I include all of them in a component?
At the moment, I'm starting to notice that although AngularDart components help with making components reusable, they are not the most maintainable - there's lots of copy paste in CSS. If it was possible to split the styles the components would be a lot more maintainable (i.e. One can include base styles in multiple components - instead of copy-pasting them across every css file for each component).
What is the best way to structure components and css within AngularDart environment?
The attribute cssUrl and applyAuhtorStyles can both be applied at the same time, as shown below. As you can see, in addition to inheriting the parent styles (bootstrap for example), you can also add component specific styles (cssUrl) that are only available in the component scope.
#NgComponent(
selector: 'paginate',
templateUrl: 'component/paginate/paginate_component.html',
cssUrl: 'component/paginate/paginate_component.css',
applyAuthorStyles: true,
publishAs: 'ctrl',
map: const {
'page-filter-map' : '<=>pageFilterMap'
}
)
There are also directives that can be used called cssStyle to add even more control, also shown below.
<span ng-style="{color:'red'}">Sample Text</span>
Ok, here's the answer. To get a css into a component you can either use
#import in your css
cssUrls parameter -
https://github.com/angular/angular.dart/pull/315
If you look here:
https://github.com/angular/angular.dart.tutorial/tree/master/Chapter_04/lib/rating
In the .dart file of the component there is an annotation that contains the attribute cssUrl. I am not sure but I think this couples the file to the encapsulating Web Component css.
#NgComponent(
selector: 'rating',
templateUrl: 'packages/angular_dart_demo/rating/rating_component.html',
cssUrl: 'packages/angular_dart_demo/rating/rating_component.css',
publishAs: 'ctrl',
map: const {
'max-rating' : '#maxRating',
'rating' : '<=>rating'
}
)
Note that in order for this packages/ link to work you need to have your files in the /lib folder.

Pseudo elements in Angular5

Why are regular pseudo-classes from CSS in Angular5 not working properly? I know that you can mimmic their behaviour using the Angular event handlers like (click)="function1()" or (mouseenter)="function2()".
What is the reason we can't use regular CSS pseudo-classes in Angular?
CSS is working just fine with Angular.
That said, Angular encapsulates the CSS for the current component you're working on (without you having to worry about that). It's a feature that you get with shadow DOM but as not all the browsers supports that, Angular is emulating it by adding properties on your components like that:
<div _ngcontent-c6>... your content ...</div>
And the original CSS you wrote is then changed by angular to:
div[_ngcontent-c0] {
color: red; // for example
}
So if you want to write some CSS that will affect other components and not just the current one, you should set the view encapsulation to none:
#Component({
selector: '...',
templateUrl: '',
styleUrls: [''],
encapsulation: ViewEncapsulation.none
})
Or, if you have an angular cli project, you can also define the global styles in: styles.scss (or .css) file which doesn't have any view encapsulation.
See more here: https://angular.io/guide/component-styles#view-encapsulation
(But before turning that feature off, think twice about it as it's really useful)

Resources