oser
oser

Reputation: 37

How to prevent Angular element (web component) from overriding the style of its parent

I have some issue with my Angular web component. My angular application contains the web component as a child, but the issue is the css of the child component is also applying to its parent.

For instance, in web component, there's some style on its body tag. However, it is also overriding the style of its parent. Is there any way to avoid this?

<div id="my-app">
  <webcomponent></webcomponent>
</div>

Upvotes: 0

Views: 2101

Answers (2)

Robert
Robert

Reputation: 27

I've used :host ::ng-deep successfully to achieve what you're looking for.

For the CSS inside web component, add :host ::ng-deep prior to your CSS element. Ex: :host ::ng-deep .my-class { color: blue }

From the docs, 'In order to scope the specified style to the current component and all its descendants, be sure to include the :host selector before ::ng-deep'

Docs: https://angular.io/guide/component-styles#deprecated-deep--and-ng-deep

Upvotes: 0

trueunlessfalse
trueunlessfalse

Reputation: 1233

If you have built your webcomponent with Angular Elements, you can make use of dom / style isolation by setting ViewEncapsulation to ShadowDom:

import { Component, ViewEncapsulation } from "@angular/core";

@Component({
  selector: "webcomponent",
  template: `
    <h3>Webcomponent</h3>
  `,
  styleUrls: ["./webcomponent.css"],
  encapsulation: ViewEncapsulation.ShadowDom
})
export class WebcomponentComponent {}

Please notice that by using shadow dom, you will also not be able to style html inside the component from outside the component.

Upvotes: 2

Related Questions