Shadowdom-Encapsulating private styles
ANGULAR2 uses shadowdom as the rendering basis for the component, which means that the component is rendered to a separate shadow tree, which is good for good encapsulation of DOM objects and styles:
The problem is that most browsers, except for Chrome, do not currently support Shadowdom, so ANGULAR2 provides three strategies for rendering templates to the DOM.
Taking the following template as an example, we look at the difference in rendering results under three strategies:
1 @View {2 Template: ",3 styles:["H1{color: Red} "]4 }
Global Simulation Strategy/emulatedunscopedshadowdomstrategy
With this strategy, ANGULAR2 inserts the template directly into the DOM tree and inserts the template's style into the head header intact . This means that styles may conflict between different components: In the example code on the right, you can see clearly that the H1 style of the Ezapp component pollutes the other H1 elements, and all H1 turn red.
The sample code renders the following DOM:
This policy does not require browser-native support for Shadowdom, which is the default policy for the current version (alpha.28).
Scope emulation Strategy/emulatedscopedshadowdomstrategy
With this strategy, ANGULAR2 inserts the template directly into the DOM tree, redefining the CSS selection for the template's style specifier inserting the head header. Because the styles are renamed, the styles between the different components do not conflict .
The result of the sample code rendering under this strategy is:
This strategy also does not require browser-native support for Shadowdom.
Native Strategy/nativeshadowdomstrategy
With this strategy, ANGULAR2 will build a shadowdom tree on the component's host DOM object, which is isolated from the main DOM tree, so this is the ideal solution for implementing Web Components:
If the browser natively supports Shadowdom, then this policy should be used.
For example:
1<!doctype html>234<meta charset= "Utf-8" >5<title>template-shadowdom strategy</title>6<script type= "Text/javascript" src= "Lib/[email protected]" ></script>7<script type= "Text/javascript" src= "Lib/angular2.dev.js" ></script>8<script type= "Text/javascript" src= "Lib/system.config.js" ></script>9Ten<body> One A<ez-app></ez-app> - -<script type= "Module" > theImport {Bind,component,view,bootstrap} from "Angular2/angular2"; - -@Component ({selector: "Ez-app"}) - @View ({ +Template: ", -styles:["H2{color:red}"] + }) A class ezapp{} at - Bootstrap (Ezapp); - -</script> -</body> -The results are as follows:
ANGULAR2 component Development-Applying styles to templates (ii)