Using Shadow DOM with View Factory

Hello,

I’m using ViewFactory to dynamically create some views and I want to inject scoped CSS into these views. I tried using the following code but the CSS leaks to the whole DOM:

var viewFactory = this.viewCompiler.compile(’’ + this.item.css + ‘’ + this.item.html + ‘’, this.viewResources);

How can I get the CSS to not leak using ViewFactory?

Thanks,
Samir

1 Like

You need to pass in additional compileinstructions to the compile method. Take a look at the implementation https://github.com/aurelia/templating/blob/master/src/view-compiler.js#L60

1 Like

Here’s an example: https://codesandbox.io/s/shadow-dom-html-only-dynamic-template-jqgdw

If you want to create views from a view factory and add to an element, you need to create the view slot with the right signal, something like this:

const viewSlot = new ViewSlot(hostElement, /* append instead of insert */ true)

Now because you want the style not to leak out, so the host element needs to be inside a shadow root, or a shadow root itself, so you should do:

const viewSlotHost = hostElement.attachShadow({ mode: 'open' });
const viewSlot = new ViewSlot(viewSlotHost, true);

And then you can do:

const viewFactory = viewCompiler.compile('<template>Some html with binding syntax</template>');
const view = viewFactory.create();

view.bind(bindingContext, overrideContext);
viewSlot.add(view);

Example: https://codesandbox.io/s/shadow-dom-html-only-dynamic-template-jqgdw

1 Like

Ok, so, at the end the only thing you did to solve the “scoped css problem” was wrapping up your style under a class, right?

1 Like

If you want your CSS not to leak “out”, you need to put it inside a shadow dom root. That’s what I was suggesting. The classes were just for having some colorful stuff for demo purposes

1 Like

Gotcha!
This discussions are a great place to learn, by the way.

1 Like

Tip for greater way to learn: create more Q topics :smiley: :kissing_heart:

EDIT: i modifed the example a bit by adding <style> h1 { color: red } </style> to show that the style from outside won’t leak into the shadow root either

1 Like