Explain Codes LogoExplain Codes Logo

What to use in place of ::ng-deep

html
css-variables
responsive-design
web-development
Alex KataevbyAlex Kataev·Sep 30, 2024
TLDR

Transition ::ng-deep to using component-specific styles leveraging :host or :host-context for CSS scoping. Adopt CSS Variables for global theming that cuts across shadow boundaries, presenting a sustainable alternative.

/* Scoped component styles */ :host(.example-class) .inner-component { color: blue; /* Making .inner-component blue within .example-class. Isn't it cool? */ } /* CSS Variables for global theming */ :root { /* Global variable, don't get too attached, it might see other components */ --theme-color: blue; } .inner-component { /* The new black? It's blue! */ color: var(--theme-color); }

As ::ng-deep is on a sunset cruise, turn your attention towards style encapsulation and angular's ShadowDOM-esque theming. ::ng-deep was merely a band-aid prior to the advent of a mainstream solution for styling shadow DOM content suavely.

CSS Variables: Your design palette

Embrace CSS Variables for your global theming endeavors. Define them at a centralized theme park (:root selector) in your CSS. It maintains a user-friendly theming experience by providing encapsulated styles, yet indulges in some global theming shenanigans.

Scoped Styles: Surgical precision for components

Reminder for your ViewEncapsulation strategy sessions: ViewEncapsulation.None signals global applicability, whereas ViewEncapsulation.Emulated makes sense for scoped styles.

Word to the wise – wrap your styles in the parent component selector within the global styles file, as a shield against accidental global side-effects.

Directives: When you crave dynamic styles

Fancy dynamic styles? Directive-based styling is your friend, ensuing a scoped, programmatic approach that avoids the hits and misses of ::ng-deep.

Consider a directive to stretch a component width to 100%; this directive acts as a stylist for your host element's styles, on demand!

Shadow Parts: Custom properties to the rescue

Up for some custom component styling? Have a go at shadow parts (::part) and flex CSS variable muscles within your web components. Anticipate stylable sections tailor-made for applying come-hither styles.

Adjacent Sibling Combinator: The router-outlet trick

With the adjacent sibling combinator (+) in your CSS toolkit, you can apply styles to those elusive Angular-generated elements (the shy ones near your router-outlet). This method fills the gap in your style's reach, without encroaching on your component's private space.