Home > Software design >  How to turn off ViewEncapsulation only for specific HTML element in the component in Angular
How to turn off ViewEncapsulation only for specific HTML element in the component in Angular

Time:05-20

I know I can disable ViewEncapsulation for the whole component with:

import { ViewEncapsulation } from '@angular/core';
...
encapsulation: ViewEncapsulation.None

However, I would like to keep the ViewEncapsulation on the component, but disable it only for some of the HTML elements in the component.

For example:

<div>
...
  <p id="disable_view_encapsulation">...</p>
</div>

How I can disable ViewEncapsulation only for the <p> tag with id="disable_view_encapsulation"?

CodePudding user response:

It's quite a tricky question because you're adding your styles so they're available for all elements.

The easiest way would be to change your styles to match what you need.

Another way is to create some kind of custom directive that would reset styles for chosen elements but oh well you're left with default styles. I don't see how many changes you need and how complex it would be so it's hard to say if we could generalize it in the directive.

Well, you could give it a try with a custom component wrapper, which would get your HTML as input and display it. If we have a new component we can set its ViewEncapsulation to a different value. However, in this case, you might end up with a strange style file.

To be honest I would rather make changes in styles if it is possible to keep code simple and not add more complexity to it.

CodePudding user response:

You could wrap the element in a component that you want to re-use with its view encapsulation turned off. You can't disable it for singular elements, only an entire component. There is no other way to really get around this in your case. Strange that your localization is affected by the attribute applied to the element, I would suggesting investigating why this is, and see if anyone else is using it with Angular and how they got around it.

  • Related