Skip to content

Slots in Lightning Web Components

Slots allow you to define placeholders in your template that can be filled with any markup fragment that a parent component passes into a component’s body. A component can have zero or more slots.

Note: Elements that can be inserted into slots are known as Slotable; when an element has been inserted in a slot, it is said to be slotted.

There are two types of slots:

  • Named Slots – Slots are identified by their name attribute in the body of the child component. 
Ex. <slot name="title"></slot>
  • Unnamed Slots – An unnamed slot is a placeholder for any markup that a parent component passes into the body of the child component. 
Ex. <slot></slot>

Here, I am creating the generic page header where there are named slots for the icon, title, and subtitle. While calling the c-generic-header (child) from the pageHeader.html (parent), I am passing the markup for the named slots in the child.

pageHeader.html

<template>
    <c-generic-header>
        <span slot="icon" class="slds-icon_container">
            <lightning-icon icon-name="action:announcement" title="Announcement" size="small"></lightning-icon>
        </span>
        <span slot="title" class="slds-page-header__title slds-truncate">Hello Folks!</span>
        <span slot="subtitle">Welcome to "Living The Trailead"</span>
    </c-generic-header>
</template>
genericHeader.html

<template>
    <div class="slds-page-header">
        <div class="slds-page-header__row">
            <div class="slds-page-header__col-title">
                <div class="slds-media">
                    <div class="slds-media__figure">
                        <!-- slot for icon-->
                        <slot name="icon">

                        </slot>
                    </div>
                    <div class="slds-media__body">
                        <div class="slds-page-header__name">
                            <div class="slds-page-header__name-title">
                                <h1>
                                    <!-- slot for title-->
                                    <slot name="title">

                                    </slot>
                                </h1>
                            </div>
                        </div>
                        <p class="slds-page-header__name-meta">
                            <!-- slot for subtitle-->
                            <slot name="subtitle">

                            </slot>
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

Output:

Slots in LWC
Published inCoding Mania

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *