Return to site

Web Components Slots

broken image


Web Components, instead of being a single spec, is a collection of several stand-alone Web technologies. Often Web Components will leverage Shadow DOM features. Shadow DOM is commonly used for CSS encapsulation. However, Shadow DOM has another useful feature called Slots. Web Components are generally available in all of the major browsers with the exception of Microsoft Edge and Internet Explorer 11, but polyfills exist to fill in those gaps. Referring to any of these as Web Components is technically accurate because the term itself is a bit overloaded. Allowing users of your custom elements to add their own markup and elements as part of your element is as simple as using the slot element in your component's template. Here's an example of a dumb custom element that only acts as a styled shell for content that's added when the element is used. Templates and slots let us create reusable components that we can use in Web Components. The template element does not show up during render so we can put them anywhere and use them as we wish in any Web Component.

Many types of components, such as tabs, menus, image galleries, and so on, need the content to render.

Just like built-in browser expects items, our may expect the actual tab content to be passed. And a may expect menu items.The code that makes use of can look like this:…Then our component should render it properly, as a nice menu with given title and items, handle menu events, etc.How to implement it?We could try to analyze the element content and dynamically copy-rearrange DOM nodes. That's possible, but if we're moving elements to shadow DOM, then CSS styles from the document do not apply in there, so the visual styling may be lost. Also that requires some coding.Luckily, we don't have to. Shadow DOM supports elements, that are automatically filled by the content from light DOM.Named slotsLet's see how slots work on a simple example.Here, shadow DOM provides two slots, filled from light DOM:In the shadow DOM, defines an 'insertion point', a place where elements with slot='X' are rendered.Then the browser performs 'composition': it takes elements from the light DOM and renders them in corresponding slots of the shadow DOM. At the end, we have exactly what we want – a component that can be filled with data.Here's the DOM structure after the script, not taking composition into account: Ultimate texas hold'em online real money.We created the shadow DOM, so here it is, under #shadow-root. Now the element has both light and shadow DOM.For rendering purposes, for each in shadow DOM, the browser looks for slot='..' with the same name in the light DOM. These elements are rendered inside the slots:The result is called 'flattened' DOM:…But the flattened DOM exists only for rendering and event-handling purposes. It's kind of 'virtual'. That's how things are shown. But the nodes in the document are actually not moved around!That can be easily checked if we run querySelectorAll: nodes are still at their places.So, the flattened DOM is derived from shadow DOM by inserting slots. The browser renders it and uses for style inheritance, event propagation (more about that later). But JavaScript still sees the document 'as is', before flattening.Only top-level children may have slot='…' attributeThe slot='..' attribute is only valid for direct children of the shadow host (in our example, element). For nested elements it's ignored.For example, the second here is ignored (as it's not a top-level child of ):If there are multiple elements in light DOM with the same slot name, they are appended into the slot, one after another.For example, this:Gives this flattened DOM with two elements in :Slot fallback contentIf we put something inside a , it becomes the fallback, 'default' content. The browser shows it if there's no corresponding filler in light DOM.For example, in this piece of shadow DOM, Anonymous renders if there's no slot='username' in light DOM. Casino peak hike pass.Default slot: first unnamedThe first in shadow DOM that doesn't have a name is a 'default' slot. It gets all nodes from the light DOM that aren't slotted elsewhere.For example, let's add the default slot to our that shows all unslotted information about the user:All the unslotted light DOM content gets into the 'Other information' fieldset.Elements are appended to a slot one after another, so both unslotted pieces of information are in the default slot together.The flattened DOM looks like this:Menu exampleNow let's back to , mentioned at the beginning of the chapter.We can use slots to distribute elements.

Web Components Slots

Here's the markup for :

The shadow DOM template with proper slots:

  1. goes into .
  2. There are many
  3. in the template, but only one in the template. So all such
  4. are appended to one after another, thus forming the list.

The flattened DOM becomes:

One might notice that, in a valid DOM,

  • must be a direct child of
      . But that's flattened DOM, it describes how the component is rendered, such thing happens naturally here.

      We just need to add a click handler to open/close the list, and the is ready:

      Here's the full demo:

      Of course, we can add more functionality to it: events, methods and so on.

      Updating slots

      What if the outer code wants to add/remove menu items dynamically?

      The browser monitors slots and updates the rendering if slotted elements are added/removed.

      Also, as light DOM nodes are not copied, but just rendered in slots, the changes inside them immediately become visible.

      So we don't have to do anything to update rendering. But if the component code wants to know about slot changes, then slotchange event is available.

      For example, here the menu item is inserted dynamically after 1 second, and the title changes after 2 seconds:

      The menu rendering updates each time without our intervention.

  • Web components slots online

    There are two slotchange events here:

    1. At initialization:

      slotchange: title triggers immediately, as the slot='title' from the light DOM gets into the corresponding slot.

    2. After 1 second:

      slotchange: item triggers, when a new

    3. is added.

    Please note: there's no slotchange event after 2 seconds, when the content of slot='title' is modified. That's because there's no slot change. We modify the content inside the slotted element, that's another thing.

    If we'd like to track internal modifications of light DOM from JavaScript, that's also possible using a more generic mechanism: MutationObserver.

    Slot API

    Finally, let's mention the slot-related JavaScript methods.

    As we've seen before, JavaScript looks at the 'real' DOM, without flattening. But, if the shadow tree has {mode: 'open'}, then we can figure out which elements assigned to a slot and, vise-versa, the slot by the element inside it:

    • node.assignedSlot – returns the element that the node is assigned to.
    • slot.assignedNodes({flatten: true/false}) – DOM nodes, assigned to the slot. The flatten option is false by default. If explicitly set to true, then it looks more deeply into the flattened DOM, returning nested slots in case of nested components and the fallback content if no node assigned.
    • slot.assignedElements({flatten: true/false}) – DOM elements, assigned to the slot (same as above, but only element nodes).

    These methods are useful when we need not just show the slotted content, but also track it in JavaScript.

    For example, if component wants to know, what it shows, then it could track slotchange and get the items from slot.assignedElements:

    Summary

    Usually, if an element has shadow DOM, then its light DOM is not displayed. Slots allow to show elements from light DOM in specified places of shadow DOM.

    There are two kinds of slots:

    • Named slots: .. – gets light children with slot='X'.
    • Default slot: the first without a name (subsequent unnamed slots are ignored) – gets unslotted light children.
    • If there are many elements for the same slot – they are appended one after another.
    • The content of element is used as a fallback. It's shown if there are no light children for the slot.

    The process of rendering slotted elements inside their slots is called 'composition'. The result is called a 'flattened DOM'.

    Composition does not really move nodes, from JavaScript point of view the DOM is still same.

    JavaScript can access slots using methods:

    Slots
    • slot.assignedNodes/Elements() – returns nodes/elements inside the slot.
    • node.assignedSlot – the reverse property, returns slot by a node.

    If we'd like to know what we're showing, we can track slot contents using:

    • slotchange event – triggers the first time a slot is filled, and on any add/remove/replace operation of the slotted element, but not its children. The slot is event.target.
    • MutationObserver to go deeper into slot content, watch changes inside it.

    Now, as we know how to show elements from light DOM in shadow DOM, let's see how to style them properly. The basic rule is that shadow elements are styled inside, and light elements – outside, but there are notable exceptions.

    We'll see the details in the next chapter.

    Now that we went over some of the basic concepts of Web Components and Custom Elements, let's push our exploration a little bit further and discuss attributes and properties.

    This post discusses the Custom Elements V1 spec.

    We'll start with a few important concepts about attributes and properties in the DOM:

    Properties vs Attributes

    The difference between properties and attributes can be confusing. Properties are available on a DOM node when being manipulated by JavaScript:

    And attributes are provided in the HTML itself. Here alt, width and height are all attributes:

    Attributes should only be used for scalar values like strings, numbers and boolean values. Properties, on the other hand, are perfectly suited to also hold values that are objects or arrays.

    Reflecting Properties to Attributes

    Most properties reflect their values as attributes, meaning that if the property is changed using JavaScript, the corresponding attribute is also changed at the same time to reflect the new value. This is useful for accessibility and to allow CSS selectors to work as intended.

    You can try it out yourself for a concrete example. Poker printables. Just select, say, an image element in your browser's developer tools, and then change one of its properties:

    Notice how the with attribute in the DOM representation is automatically changed to the new value. The same is true if you change the value for the attribute manually in the DOM inspector, you'll see that the property will now hold the new value.

    Reflecting properties to attributes in Custom Elements

    Lightning web components slots

    Here's the markup for :

    The shadow DOM template with proper slots:

    1. goes into .
    2. There are many
    3. in the template, but only one in the template. So all such
    4. are appended to one after another, thus forming the list.

    The flattened DOM becomes:

    One might notice that, in a valid DOM,

  • must be a direct child of
      . But that's flattened DOM, it describes how the component is rendered, such thing happens naturally here.

      We just need to add a click handler to open/close the list, and the is ready:

      Here's the full demo:

      Of course, we can add more functionality to it: events, methods and so on.

      Updating slots

      What if the outer code wants to add/remove menu items dynamically?

      The browser monitors slots and updates the rendering if slotted elements are added/removed.

      Also, as light DOM nodes are not copied, but just rendered in slots, the changes inside them immediately become visible.

      So we don't have to do anything to update rendering. But if the component code wants to know about slot changes, then slotchange event is available.

      For example, here the menu item is inserted dynamically after 1 second, and the title changes after 2 seconds:

      The menu rendering updates each time without our intervention.

      There are two slotchange events here:

      1. At initialization:

        slotchange: title triggers immediately, as the slot='title' from the light DOM gets into the corresponding slot.

      2. After 1 second:

        slotchange: item triggers, when a new

      3. is added.

      Please note: there's no slotchange event after 2 seconds, when the content of slot='title' is modified. That's because there's no slot change. We modify the content inside the slotted element, that's another thing.

      If we'd like to track internal modifications of light DOM from JavaScript, that's also possible using a more generic mechanism: MutationObserver.

      Slot API

      Finally, let's mention the slot-related JavaScript methods.

      As we've seen before, JavaScript looks at the 'real' DOM, without flattening. But, if the shadow tree has {mode: 'open'}, then we can figure out which elements assigned to a slot and, vise-versa, the slot by the element inside it:

      • node.assignedSlot – returns the element that the node is assigned to.
      • slot.assignedNodes({flatten: true/false}) – DOM nodes, assigned to the slot. The flatten option is false by default. If explicitly set to true, then it looks more deeply into the flattened DOM, returning nested slots in case of nested components and the fallback content if no node assigned.
      • slot.assignedElements({flatten: true/false}) – DOM elements, assigned to the slot (same as above, but only element nodes).

      These methods are useful when we need not just show the slotted content, but also track it in JavaScript.

      For example, if component wants to know, what it shows, then it could track slotchange and get the items from slot.assignedElements:

      Summary

      Usually, if an element has shadow DOM, then its light DOM is not displayed. Slots allow to show elements from light DOM in specified places of shadow DOM.

      There are two kinds of slots:

      • Named slots: .. – gets light children with slot='X'.
      • Default slot: the first without a name (subsequent unnamed slots are ignored) – gets unslotted light children.
      • If there are many elements for the same slot – they are appended one after another.
      • The content of element is used as a fallback. It's shown if there are no light children for the slot.

      The process of rendering slotted elements inside their slots is called 'composition'. The result is called a 'flattened DOM'.

      Composition does not really move nodes, from JavaScript point of view the DOM is still same.

      JavaScript can access slots using methods:

      • slot.assignedNodes/Elements() – returns nodes/elements inside the slot.
      • node.assignedSlot – the reverse property, returns slot by a node.

      If we'd like to know what we're showing, we can track slot contents using:

      • slotchange event – triggers the first time a slot is filled, and on any add/remove/replace operation of the slotted element, but not its children. The slot is event.target.
      • MutationObserver to go deeper into slot content, watch changes inside it.

      Now, as we know how to show elements from light DOM in shadow DOM, let's see how to style them properly. The basic rule is that shadow elements are styled inside, and light elements – outside, but there are notable exceptions.

      We'll see the details in the next chapter.

      Now that we went over some of the basic concepts of Web Components and Custom Elements, let's push our exploration a little bit further and discuss attributes and properties.

      This post discusses the Custom Elements V1 spec.

      We'll start with a few important concepts about attributes and properties in the DOM:

      Properties vs Attributes

      The difference between properties and attributes can be confusing. Properties are available on a DOM node when being manipulated by JavaScript:

      And attributes are provided in the HTML itself. Here alt, width and height are all attributes:

      Attributes should only be used for scalar values like strings, numbers and boolean values. Properties, on the other hand, are perfectly suited to also hold values that are objects or arrays.

      Reflecting Properties to Attributes

      Most properties reflect their values as attributes, meaning that if the property is changed using JavaScript, the corresponding attribute is also changed at the same time to reflect the new value. This is useful for accessibility and to allow CSS selectors to work as intended.

      You can try it out yourself for a concrete example. Poker printables. Just select, say, an image element in your browser's developer tools, and then change one of its properties:

      Notice how the with attribute in the DOM representation is automatically changed to the new value. The same is true if you change the value for the attribute manually in the DOM inspector, you'll see that the property will now hold the new value.

      Reflecting properties to attributes in Custom Elements

      Your own Custom Elements should also follow this practice of reflecting properties to attributes. Luckily, it's quite easy to do using getters and setters.

      For example, if you have a custom element that has a value property that should be reflected as an attribute, here's how you would use a getter and a setter to get the value of the attribute when doing property access and setting the new value for the attribute when the property is changed:

      Or, if you have a boolean property, like, say hidden:

      Listening for Changed Attributes

      With Custom Elements, you can listen for attribute changes using the attributeChangedCallback method. This makes it easy to trigger actions when attributes are changed. To help with performance, only attributes defined with an observedAttributes getter that returns an array of observed attribute names will be observed.

      The attributeChangedCallback is defined with three parameters, the name of the attribute, the old value and the new value. In this example, we observe the value and max attributes:

      Web Components Dynamic Slots

      Notice also that the observedAttributes getter is a static method on the class. Static methods are often used as utility methods for the class itself because they are unavailable on class instances.

      Putting it All Together

      Let's put all these concepts together by building a simple counter element, similar to the one that we build using Stencil.

      Our component can be used like this:

      Or it can be used with the following attributes:

      Here's the full code for our custom element, with a few interesting parts highlighted:

      my-counter.js

      Most of the code is pretty straight-forward and uses concepts that we discussed in this article. The highlighted parts may be new however, so here are some quick explanations:

      Web Components Slots

      • In the constructor we bind the this for our increment and decrement methods to the this of the class itself. Otherwise, since these two methods are used as callbacks for event handlers on button elements, the this would be the clicked button instead of the Custom Element.
      • In the connectedCallback method we set the value attribute to an initial value of 1 if value hasn't been set by the user of the element.
      • We remove our event listeners in the class' disconnectedCallback method.

      latest web-components posts

      Efficient Template Rendering Using lit-html

      Composing Custom Elements With Slots And Named Slots

      Styling Your Custom Elements

      Polyfills and Transpilation for Your Custom Elements

      all web-components posts





  • broken image