Host CSS classes made available to ShadowDom contents - css

As far as I can see even with mode=open CSS classes of host are not piercing through Shadow Dom.
Is it possible to make CSS classes defined outside ShadowDom available to its contents?

No, the whole point of shadowDOM is encapsulation.
If you don't want that, then do not use shadowDOM.
Web Components can be programmed to accept some Global styling with:
CSS Custom Properties
https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties
::part
https://developer.mozilla.org/en-US/docs/Web/CSS/::part

Related

What is the the scope of ::ng-deep?

A lot of our site is structured as such:
component
component CSS
component template
child component
We often need to style the child component differently based on which parent component it was in. This is annoying, of course, but was manageable when we were using global CSS as we could simply target the specific instance with unique ID and class CSS selectors.
We're trying to now stop using global styles and encapsulating our CSS within each component. The problem with this is that, from what I see, encapsulate angular CSS will scope your CSS so that it only applies to that component...which means it also will not apply to any child components.
One solution appears to be to use ::ng-deep selectors in our component CSS to target the child. This is meeting some resistance, though, as I'm being told this also breaks encapsulation in general and could affect other parts of the site in different components.
This is where I'm confused. Some questions:
Does any style targeted with ::ng-deep become descoped so that it is global application-wide? Or is it simply 'global' within that one parent component?
If it's the former, would it be an OK practice to still use ::ng-deep, but also make sure you are using additional unique css selectors so it only applies to the child component you are targeting?
Or is there a more proper way to add styles to a particular child component instance?
:ng-deep is global. No matter where you put it, it applies to all components. Not just children.
If you use :host :ng-deep, then it will work from that component down (Into the children, grand children etc).
The main issue working with ng-deep is that styles in Angular are lazy loaded. So in some cases, you can be viewing the site perfectly fine, then you view a particular page that uses ng-deep, then you can go back to previous pages that were fine that are now broken because the ng-deep style is applied site wide. e.x. https://tutorialsforangular.com/2020/04/13/the-dangers-of-ng-deep-bleeding/
Generally speaking, if I need to style a child component slightly differently depending on where it's placed, then I create an input variable for the child, make the parent set it, then make it a class somewhere in the child component HTML. The child component can then style that class how it see's fit and you haven't had to break encapsulation.
::ng-deep by itself does make the style global, but when combined with :host may do what you need, but as #eldar alluded to with this link, ::ng-deep is deprecated (and has been for some time).

Angular: Component styles do not cascade to sub-components?

In my app.component.html I have the following, working class assignment.
<body>
<span class="test">SHABOO</span>
<div class="container">
<router-outlet></router-outlet>
</div>
</body>
In the outlet, a component is rendered and it contains the following.
<span class="test">HAZAA</span>
I expected it to get the same style as the first one but it seems that the style doesn't cascade down to the component. It made me uncertain if I'm mistaken about how the styles are supposed to behave between parent and child components in Angular.
I made sure that the name of the class isn't overriden (to exclude the risk of collision). At the moment, I'm putting similar chunks of SCSS code in each component and that's obviously bad practice.
If I #import "../app.component.scss", the styles kicks in. But I was under the impression that even without the import, the style is supposed to cascade.
Angular components use view encapsulation. This is by design so that components are reusable across applications. To treat a component's styles as global, set the view encapsulation mode to none (not recommended).
Instead of using none, register global style files in the Angular CLI styles section, which is pre-configured with the styles.css file.
Component CSS styles are encapsulated into the component's view and don't affect the rest of the application.
To control how this encapsulation happens on a per component basis, you can set the view encapsulation mode in the component metadata. Choose from the following modes:
ShadowDom view encapsulation uses the browser's native shadow DOM implementation (see Shadow DOM on the MDN site) to attach a shadow DOM to the component's host element, and then puts the component view inside that shadow DOM. The component's styles are included within the shadow DOM.
Native view encapsulation uses a now deprecated version of the browser's native shadow DOM implementation - learn about the changes.
Emulated view encapsulation (the default) emulates the behavior of shadow DOM by preprocessing (and renaming) the CSS code to effectively scope the CSS to the component's view. For details, see Appendix 1.
None means that Angular does no view encapsulation. Angular adds the CSS to the global styles. The scoping rules, isolations, and protections discussed earlier don't apply. This is essentially the same as pasting the component's styles into the HTML.
To set the components encapsulation mode, use the encapsulation property in the component metadata:
src/app/quest-summary.component.ts
// warning: few browsers support shadow DOM encapsulation at this time
encapsulation: ViewEncapsulation.Native
ShadowDom view encapsulation only works on browsers that have native support for shadow DOM (see Shadow DOM v1 on the Can I use site). The support is still limited, which is why Emulated view encapsulation is the default mode and recommended in most cases.
External and global style files
When building with the CLI, you must configure the angular.json to include all external assets, including external style files.
Register global style files in the styles section which, by default, is pre-configured with the global styles.css file.
See the CLI wiki to learn more.
This is how angular works. Every component is separated with it's CSS, even if it is child component of a parent. They can't inherit their parent CSS.
Haza span component is child of your app component, but it is separated component. So, you can't get those Shaboo styling to Haza.
Solution:
if you want to maintain same CSS, there are multiple ways.
Recommended way:
a) if it is only for onle class, copy the class to the child component.
b) if it is for huge number of classes, create a css file for them and import them in both parent and child component css.
Example:
#import '../span.css';
you can add this css to styles.css. then you will get it anywhere in the app. if you want this style many places, you can do it.
As #Christopher Peisert mentioned, by using
encapsulation: ViewEncapsulation.Native
end of the #component decorator in child.component.ts. It is not recommended way
The global CSS files are those that are listed in angular.json. All others CSS files are encapsulated by default (this can be removed but is not recommended.)
Keeping your global CSS organised is important as your application grows. What I like to do is create a global styles folder and then add new files for different widgets that I might be altering. Since removal of ::ng-deep these types of changes have to be done in the global scope.
It works like that. If you are in need of having a common style then add it in the global styles.scss file.
If you want a global style put it in the global file styles.css or styles.[Your css preprocessor]
See this example https://stackblitz.com/edit/angular-a5ntm6?file=src%2Fstyles.css
I put test class at the end
.test{
color:red;
}

Angular2 change parent styles outside of component

I'd like to change the styles of a component outside the scope of my current component. The markup in my app.component.html is as follows:
<app-nav></app-nav>
<div id='content-container'>
<router-outlet></router-outlet>
</div>
I'm looking to change the styles of a class main-nav in the app-nav component from the 'home-component' which is loaded from a route. I use routerLink's in the nav and I've found if I add encapsulation: ViewEncapsulation.None to the home.component.ts I can alter the styles of the the class in the app-nav component however the changes are only applied once and if I go to other routes using the routerLink's I cannot revert the changes (seems like the css is only loaded/applied once - when the component is initialized/comes into view)
Special selectors are designed to access and apply css outside the encapsulation without having to change encapsulation scope. In your case I think :host or :host-context will help.
See https://angular.io/guide/component-styles#special-selectors
Use the :host pseudo-class selector to target styles in the element
that hosts the component (as opposed to targeting elements inside the
component's template).
and
Sometimes it's useful to apply styles based on some condition outside
of a component's view. For example, a CSS theme class could be applied
to the document element, and you want to change how your
component looks based on that.
Use the :host-context() pseudo-class selector, which works just like
the function form of :host(). The :host-context() selector looks for a
CSS class in any ancestor of the component host element, up to the
document root. The :host-context() selector is useful when combined
with another selector.
change the styles of a component outside the scope of my current component
Before I say anything else, this is highly discouraged. Components are supposed to be self-contained entities, which can be reusable across your project, or even other projects. By creating a component that changes something else in the system only through CSS, you're creating a tight coupling which is difficult to see immediately from code, leading to difficult-to-debug bugs and other errors.
If you want to change your app-nav (or main-nav as you refer to it later, I'm not sure if this is my mistake) based on the current route, you should do so by injecting the ActivatedRoute and querying it to determine the specific version of header which you want.
Another option is to simply move the header below the router outlet, so you always direct access to it from the component which rests across the whole page.
the changes are only applied once and if I go to other routes using the routerLink's
This is expected, since the styles are injected into DOM only when you visit the actual component, no need for them to appear before there's need for it. Angular expects that the styles you define for a component and used only on that component. You're breaking this rule of thumb.
I cannot revert the changes (seems like the css is only loaded/applied once - when the component is initialized/comes into view)
Your observation is correct.

Styling shadow DOM with external

Given a webpage with dynamically loaded web components (shadow DOM) and some external CSS files (Bootstrap, etc.). I want these CSS files to be applied within the components (shadow DOM). What are the possible solutions?
Using Polymer -- we're already using AngularJS and don't wanna start messing with another framework too. (Although it's possible.)
Refactoring the CSS files and include /deep/ everywhere -- maintainability...
Import each CSS file manually into the beginning <style> part of each shadow DOM -- no comment...
Is there any better way to apply whole CSS files within shadow DOMs?
Question is a bit old, but putting this answer here in case it helps.
/deep/ has been deprecated
Other option is to use custom properties provided by Polymer.
If you don't want to use Polymer then as suggested in the discussion on the /deep/ and ::shadow selectors deprecation thread, you can you use css #imports.
You can generate the url of your external stylesheet and inject it in your shadow dom templates at run-time.
I have written a descriptive answer here on the topic.

How should a JavaScript library set default CSS styles (is there a "!notimportant"?)

When a JavaScript library creates a <div>, it typically sets a class on the div so that the user of the library can style it him/herself. It's also common, however, for the JS library to want to set some default styles for the <div>.
The most obvious way for the library to do this would be with inline styles:
<div style="application's default styles" class="please-style-me">
...
</div>
However, this will make the application's default styles trump the user's styles. A workaround is to use nested divs:
<div style="application's default styles">
<div class="please-style-me">
...
</div>
</div>
This works great for many styles like 'font' but fails for others like 'position', where the inner div's style will not override the outer div's.
What is the best practice for creating user-stylable elements with defaults in a JavaScript library? I'd prefer not to require users to include a CSS file of defaults (it's nice to keep your library self-contained).
When a JS library has a default set of styles that should be used, but should also be overridden, the JS library should include a separate stylesheet.
JavaScript should avoid adding styles directly as much as possible, and defer all styling to CSS where it's reasonable.
It's common for sets of styles to be toggled on and off. The way to elegantly handle these situations are with CSS classes.
A case where it may not be reasonable to simply use external stylesheets is animation. CSS animations could certainly be used, but for cross-browser support, asynchronous interpolation is used to animate styles from one value to another.
There isn't !notimportant or !unimportant in CSS. And I haven't run into an accepted best practice. It seems like a CSS file is the defacto standard for styles that should be user modifiable.
But if you want to keep things all in one library, I would take your second example, with your application default styles, then append a CSS class to it and prepend something unique to the class name. Then if the implementor wants to override your styles, the implementor could just use !important to override your user styles.
Adding !important to one or two styles in a CSS file shouldn't be a huge deal, but if you're creating a bunch of inline styles, this may not be the best solution.

Resources