Im struggling to do something that seems like it should be simple. I am creating my first web component and it cannot be within the shadowDOM. I need it to receive some dynamic content and inject it into the correct div like so:
<component>
<div id="one"><!-- Dynamic Content ends up here --></div>
<div id="two">...</div>
</component>
This is simple using slots in shadowDOM, why is it proving difficult in lightDOM? Any help is appreciated.
You problem is essentially about using
slotswithout Shadow DOM. Unfortunately, there is no out-of-box solution for this problem. You can use combination of<template>tag and component props:And, then for each instance of the
<component />, you will clone the template usingcloneNodemethod. And, then you append this Node as a child of your custom component. You can augment the DOM however you like.Now, second part of the equation is adding the dynamic content to the
div#oneanddiv#two. For this purpose, you should declare the twopropsover the component and the caller will pass the content. The web component will then append that content viaDocumentFragment,innerHTMLor other DOM APIs. This is roughly similar to what vDOM based frameworks likeReact,Vuedo. The only difference is instead of passing real DOM, it passes virtual tree as achildrenorrenderprop.So, without a proper framework, this is a lot of work. I would recommend you consider using Shadow DOM and keep the Shadow Root
open.