Blog>
Snippets

Styling Angular Elements in a Non-Angular Context

Present a method for applying CSS styles to Angular Elements from outside the Angular project, explaining how to preserve encapsulation and prevent style leakage.
customElements.define('my-angular-element', MyAngularElementComponent);
This line of code registers the custom element 'my-angular-element' with the browser, allowing it to be used in non-Angular contexts. The 'MyAngularElementComponent' is the class exported from the Angular application after being converted to a custom element.

// Add this style to the global stylesheet or in a <style> tag in your non-Angular HTML
::ng-deep my-angular-element {
  --custom-background-color: #f0f0f0;
  --custom-text-color: #333;
}
The '::ng-deep' pseudo-class is used here to define CSS variables on the 'my-angular-element' custom element. These variables can be used as a theming mechanism, which the Angular component inside the custom element can make use of, without causing style leakage to other parts of the DOM.

// Inside the Angular component's stylesheet or styles metadata
:host {
  background-color: var(--custom-background-color);
  color: var(--custom-text-color);
}
Inside the Angular component's styling, the ':host' pseudo-class selector targets the host element of the component, which in this case is the custom element itself. CSS variables (--custom-background-color and --custom-text-color) are used to apply the styles supplied from the non-Angular context, thus preserving style encapsulation.