Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular full encapsulation when creating a hosted angular widget

Tags:

angular

I have an angular widget that should be embedded in different sites and I have no knowledge about the sites that will embed it.

I cannot place the widget in an IFrame.

This means that the widget should be 100% encapsulated.

The widget is using components from certain libraries like:

angular bootstrap - https://angular-ui.github.io/bootstrap/

@angular/material

Some of the components from those libraries are using view encapsulation set to none which means one problem will be that my head will contain stuff like:

.mat-checkbox {...}

which is not good cause it might interfere with the host site styles.

Another problem is that I cannot afford class names like .mat-checkbox cause this means that the host site can load a material design template and change my widget appearance.

I examined other companies solution like hotjar

they do not place in iframe and they simply hash their classnames (probably using a library for css in js like typestyle or postcss) which is a great solution for me - but

how do i hash the classnames of the components from 3rd party libraries like material design and angular bootstrap?

Things I tried:

  • Angular elements for creating a web component

  • Typestyle

like image 732
Yariv Katz Avatar asked Mar 21 '19 07:03

Yariv Katz


People also ask

What is encapsulation in Angular?

In Angular, a component's styles can be encapsulated within the component's host element so that they don't affect the rest of the application. The Component 's decorator provides the encapsulation option which can be used to control how the encapsulation is applied on a per component basis.

What is ViewEncapsulation native in Angular?

In the browser, when you examine source code, you will a Shadow DOM has been created for the AppComponent and the style is scoped to that. Therefore, in ViewEncapsulation. Native , Angular creates a Shadow DOM and the style is scoped to that Shadow DOM.


2 Answers

You have written you have tried angular elements but didn't mention if you face any problem with it. I am creating a project which lives in other's project and analyze their project at run time. For me, the angular element was a perfect fit. If you use encapsulation: ViewEncapsulation.ShadowDom in your root component, your styles will automatically be scoped. You can use them in non angular project as well.

like image 152
dasfdsa Avatar answered Oct 06 '22 01:10

dasfdsa


One thing you could try, which is not that Angulary is to use TreeWalker to go over all of the nodes in your widget in ngAfterViewInit lifecycle hook and alter classes using Renderer2 in a way you like. TreeWalker is supported by domino so it should even work with Angular Universal.

like image 32
waterplea Avatar answered Oct 06 '22 00:10

waterplea