Composing Nested Web Components v1

I am new to web components. Since v1 web components are available, I start there. I read various posts on the Internet about them. I am especially interested in compiling them correctly. I read about the slots and made them work, although my efforts did not result in the use of slot web components that work as I expected.

If I have nested web components like this, the DOM from the nested / slot web component is not inserted into the parent slot:

<parent-component> <child-component slot="child"></child-component> </parent-component> 

And here is the parent HTML web component:

 <div id="civ"> <style> </style> <slot id="slot1" name="child"></slot> </div> 

Since each web component (parent and child) is written as independent, I created them using

 customElements.define('component-name', class extends HTMLElement { constructor() { super(); this.shadowRoot = this.attachShadow({mode: 'open'}); this.shadowRoot.innterHTML = `HTML markup` } }) 

As a result, the DOM contains 2 shadow roots. I tried to write child / slot elements without shadow dom, which also does not cause the parent shadow house to place child elements.

So, what is the correct way to build v1-nested web components?

+6
source share
1 answer

You must first use a browser that implements Shadow DOM and Custom Elements v1 .

Then calling attachShadow() will automatically assign the new Shadow DOM to the read-only object.

You can add HTML code to the Shadow DOM innerHTML , but I would recommend using the <template> content property instead.

Then nesting is natural:

 customElements.define( 'parent-component', class extends HTMLElement { constructor() { super() this.attachShadow( {mode: 'open'} ) this.shadowRoot.appendChild( parent1.content.cloneNode( true ) ) } } ) customElements.define( 'child-component', class extends HTMLElement { constructor() { super() var sh = this.attachShadow( {mode: 'open'} ) sh.appendChild( child1.content.cloneNode( true ) ) } } ) 
 <parent-component> <child-component slot="child"> <span>Hello</span> </child-component> </parent-component> <template id="parent1"> <style> :host { background: lightblue ; display: inline-block } ::slotted( [slot=child] ) { background: lightyellow } </style> <h4>(parent)</h4> <p>Slotted child: <slot name="child"></slot> </p> </template> <template id="child1"> <style> :host { display: inline-block } ::slotted( span ) { background: pink } </style> <h5>(child)</h5> <span>Nested slot: <slot></slot></span> </template> 

In the <style> tags use:

  • :host to style the most custom item and
  • ::slotted() to style elements inserted with the <slot> .
+4
source

All Articles