angularweb-componentangular-elementsnative-web-component

Styling default slot in webcomponents


In webcomponents, we have two type of slots (named slots and default slots). We can easily style named slots by using syntax slot[name]::slotted(*). But is there any way that we can style default slots because they don't have any name associated?

The code is something like this and i'm using Angular Elements.

<div class="topbar-item">
  <slot class="icon" name="icon"></slot>
  <span class="text">
   <slot></slot> <-- This is the slot i want to add styles, only if the slot has some data assigned. (need to add margin-left)
  </span>
</div>

Solution

  • Found a little workaround until someone finds a better way. We can use slotchange event to make sure whether any items attached to the slot or not. In this way.

    HTML

    <slot (slotchange)="onSlotChanged($event)"></slot>
    

    JS/TS

        onSlotChanged($event) {
           const slotHasData = $event.target.assignedNodes().length > 0;
           // Is event.target.assignedNodes().length return more than 0, it has nu of items attached to the slot
        }