Explain the difference between Emulated, ShadowDom, and None.
Angular's view encapsulation determines how a component's styles interact with styles from other components and the global styles of the application. It controls the scope of CSS styles, ensuring that styles defined for a component either remain isolated or affect other parts of the DOM.
Emulated (Default)
This is the default view encapsulation mode in Angular. When a component uses ViewEncapsulation.Emulated, Angular modifies the component's CSS styles to make them scoped to that component only. It achieves this by adding unique _ngcontent and _nghost attributes to the component's host element and all its descendant elements, and then appending corresponding attribute selectors to the component's CSS rules. This effectively 'emulates' native Shadow DOM behavior in non-Shadow DOM environments, preventing styles from leaking out or in from other components, while still allowing global styles to affect the component.
ShadowDom (Native Shadow DOM)
With ViewEncapsulation.ShadowDom, Angular leverages the browser's native Shadow DOM API. Each component effectively becomes its own Shadow Root, which creates a truly isolated subtree in the DOM. Styles defined within a component's Shadow DOM are completely encapsulated and cannot leak out to affect other parts of the document, nor can global styles or styles from other components leak in, unless explicitly designed to do so (e.g., using CSS custom properties). This provides strong style isolation, but it relies on browser support for Shadow DOM.
None (No Encapsulation)
When ViewEncapsulation.None is selected, Angular provides no view encapsulation. The component's styles are simply added to the global style sheet (typically in the <head> of the document). This means that the component's styles become global and will affect any element in the application that matches their selectors, regardless of whether that element is part of the component or not. Conversely, any global styles or styles from other components can easily affect this component. This mode can lead to styling conflicts and maintainability issues, but it can be useful in specific scenarios where global styling is desired or for overriding third-party library styles.