liveBook · Manning

View encapsulation

As explained in Pro Angular 16

View encapsulation is Angular's mechanism for scoping component styles and, when applicable, rewriting their selectors to isolate them from other components.

View encapsulation scopes component styles and can rewrite selectors so styles remain isolated from other components. Component SCSS is attached through the component metadata and processed into browser-ready CSS during the build. section 28.3.2

The :host selector targets the component’s host element. It is needed when a component state, such as a disabled customButton element, must affect styles inside the component. section 28.3.2

Styling a disabled custom button

A custom button stylesheet combines the host selector with an internal button selector: :host[disabled] button[class*="custom-button-"]. This lets the component respond to a disabled attribute on its host while styling the contained button. The component loads the stylesheet with styleUrls: ["customButton.component.scss"].

Encapsulation also affects third-party-generated elements. Angular Material’s ripple directive inserts a div with the mat-ripple-element class; ::ng-deep prevents encapsulation from modifying that class selector so the ripple can be styled. section 28.3.3

Styling a Material ripple

Import MatRippleModule, apply matRipple to the button, and use ::ng-deep when defining the ripple style. The custom button can then retain its encapsulated component styles while reaching the generated ripple element. section 28.3.3

How Pro Angular 16 covers it

How deep it goes
Explains host selectors, generated-element access, and build-time stylesheet processing without detailing Angular’s selector-rewriting algorithm.
Examples
Demonstrates disabled custom-button styling and Angular Material ripple styling through :host, ::ng-deep, SCSS, and component metadata.
What it assumes
Assumes Angular components, component metadata, CSS selectors, and SCSS; demonstrates host styling and stylesheet attachment in context.
What you can do after
Apply it via Angular component styles to isolate custom-button rules and selectively style host or generated child elements.
How it connects
Connects component styles with SCSS, CSS selectors, Angular Material themes, directives, and component host elements.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.