Monday, April 20, 2020

Slots in LWC

Add a slot to a component’s HTML file so a parent component can pass markup into the component. A component can have zero or more slots.
A slot is a placeholder for markup that a parent component passes into a component’s body. 
To define a slot in markup, use the <slot> tag, which has an optional name attribute.
Below analogy between aura components and web components would give a clear picture of slots.

In the aura component, you used facets and body attribute to received data in the component body and now we are using slots to get it done.
In the below code we placed the content in the body of a child but to see the output we need to specify {!v.body} in the markup or you need to use body attribute in the javascript and parse it and supply it to the markup.
Parent cmp: 
<aura:application >
    <!--no logic in any of the bundle files -->
    <c:childbody >
        Parent data 1..
    </c:childbody>
</aura:application>
childbody cmp:
<aura:component >
    <!--no logic in any of the bundle files -->
{!v.body}
</aura:component>
Below code explains Slots of web components.
Parent webcmp:
<template>
  <!-- I dont have any business logic in the javascript, so ignoring it-->

  <my-childslot>
   <p>From the parent, we are passing data </p>

   <span slot="f1">Parent span </span>

   <div slot="f2">Parent f2 span </div>
  </my-childslot>

</template>

childbody.html webcmp:
<template>

<slot></slot>

<b><slot name="f1">   </slot> </b>
<h1><slot name="f2">   </slot> </h1>

</template>

childbody.js webcmp
import { LightningElementtrackfrom 'lwc';

export default class Childslot extends LightningElement {
    renderedCallback(){
   // Below line will not work as span element is not there in its template
   // console.log("$$$span query selector$$$$"+this.template.querySelector('span').innerHTML);
    
   //Below code works by removing template.
   console.log("$$$span query selector$$$$"+this.querySelector('span').innerHTML);

    }

}

The output of web component as follows:
To access the elements passed into the childbody, you need to use syntax as below. Note you should not use this.template while accessing the elements passed via slot.
this.querySelector('anyelement')

No comments:

Post a Comment