Remove component tag in StencilJS

1.6k Views Asked by At

I'm trying to remove the called component tag from HTML to prevent some broken CSS from external libraries and just show the inner content.

something.component.html

<div>
    Hello World
</div>

another.component.html

<div>
   <app-something [config]="somethingConfig"></app-something>
</div>

Then outputs:

 <div>
    <app-something>
      <div>
          Hello World
      </div>
    </app-something>
</div>

And I want:

<div>
  <div>
     Hello World
  </div>
</div>

2

There are 2 best solutions below

1
On

This is not possible due to the nature of web components which Stencil outputs.

What you could do instead: use the CSS rule display: contents on your component which prevents it from generating a box in the layout (see https://caniuse.com/css-display-contents, still somewhat experimental).


There are also functional components in Stencil (https://stenciljs.com/docs/functional-components) which don't generate a parent element, but those are only available within JSX, so you'll always need at least one parent Stencil component (so that you can render some JSX).

0
On

A ugly one but it works:

// removing the parent wrapper element
removeParentWrapper() {
  // Find an element with the tag name
  const wrapperNode = document.querySelector('app-something');
  if (wrapperNode) {
    // Create a temporary fragment to hold the child nodes of the found element
    const fragment = document.createDocumentFragment();
    // Move each child node from the found element to the fragment
    while (wrapperNode.firstChild) {
      fragment.appendChild(wrapperNode.firstChild);
    }
    // Replace the found element with its child nodes
    wrapperNode.replaceWith(fragment);
  }
}

componentDidLoad() {
  this.removeParentWrapper();
}

As said, this works but some reactive functionality will get effected, also - if this component is listening (@Listen) to any emits, then this doesn't work, it's good to use this only with static component.