Category: Lightning Web Components

Usage Of lightning-record-form

Let us discuss here how to use the lightning-record-form . A lightning-record-form component enables you to quickly create forms to add, view, or update a record. Using this component to create record forms is easier than building forms manually with lightning-record-edit-form and lightning-record-view-form. However, lightning-record-form does not support client-side validation quite the same as lightning-record-edit-form.The object-api-name attribute is always required, and the record-id is required unless you’re creating a record.

Modes

The component accepts a mode value that determines the user interaction allowed for the form. The value for mode can be one of the following:

  • edit – Creates an editable form to add a record or update an existing one. When updating an existing record, specify the recordId. Edit mode is the default, and as such, can be omitted.
  • view – Creates a form to display a record that the user can also edit. The record fields each have an edit button.
  • readonly – Creates a form to display a record without enabling edits. The form doesn’t display any buttons.

For all modes, the component expects the fields attribute, the layout-type attribute, or both. Use the fields attribute to specify a comma-separated list of record fields to load into the form. The fields load in the order you list them. Use the layout-type attribute to specify a Full or Compact layout. All fields that have been assigned to the layout are loaded into the form. This is the same behavior as the Lightning Data Service’s force:recordData object. Layouts are typically created or modified by administrators. Loading record data using layout-type allows the form to adapt to those layout definitions. If you provide the fields attribute and the layout-type attribute, the fields specified in the fields attribute are loaded before the layout fields.

This component takes care of field-level security and sharing for you, so users see only the data that they have access to.

Creating a Record

Use mode="edit" and pass in the object API name for the record to be created. Do not specify a recordId. Specify the fields using the fields attribute, or layout-type="Full" attribute to load all the fields defined on the full layout.The compact layout cannot be used for creating records. If you specify layout-type="Compact", the full layout is shown. If you specify the fields attribute, be sure to include any fields that are designated as required for the object’s records. Because no recordId is passed, edit mode loads the form with input fields that aren’t populated with field data. The form displays Submit and Cancel buttons.This example creates an editable two-column form with the full layout and additional fields. The form is used for creating records in an Account object. The onsubmit attribute specifies an action to override the handler for the submit.

Create a Lightning web component using the below SFDX command

sfdx force:lightning:component:create --type lwc --componentname recordform --outputdir force-app\main\default\lwc

Use the below recordform.html code

<template>
    <lightning-record-form object-api-name="Account" layout-type="Compact" columns="2" mode="edit" 
    onsuccess={handleSuccess} onsubmit={handleSubmit}>
    </lightning-record-form>
</template>

Use the below recordform.js code

import {
    LightningElement,
    api
} from 'lwc';

export default class Recordform extends LightningElement {

    handleSubmit(event) {
        console.log(event.detail)
    }
    handleSuccess(event) {
        console.log('Record iD' + event.detail.id);

    }
}

Use the below recordform.js-meta.xml code

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 

Push the changes and add this component to the record page layout. you can able to see the complete record create a form

 

Now let’s see how to use create a record with specific fields. Now update the recordform.html code as shown below

<template>
    <lightning-record-form object-api-name={accountObject}  fields={myFields} mode="edit"
        onsuccess={handleSuccess} onsubmit={handleSubmit}>
    </lightning-record-form>
</template>

Use the below recordform.js code which will be passed to the record form.

import {
    LightningElement,
    api
} from 'lwc';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import WEBSITE_FIELD from '@salesforce/schema/Account.Website';
export default class Recordform extends LightningElement {

     accountObject = ACCOUNT_OBJECT;
     myFields = [NAME_FIELD, WEBSITE_FIELD];
     
    handleSubmit(event) {
        console.log(event.detail);
    }
    handleSuccess(event) {
        console.log('Record iD' + event.detail.id);

    }
}

Push the changes and you can able to see the create form with two fields as shown below.

Editing a Record

If you do not specify the mode attribute, its default value is edit. To edit a record, pass the ID of the record and the corresponding object API name to be edited. Specify the fields using the fields attribute, or layout-type attribute to load all the fields defined on the Full or Compact layout. When record-id is passed, edit mode loads the form with input fields displaying the specified record’s field values. The form also displays Submit and Cancel buttons. This example creates an editable two-column form with a compact layout and additional fields. The form is used for editing records in an Account object. The onsubmit attribute specifies an action to override the handler for the submit. Update the recordform.html code as shown below.

<template>
    <lightning-record-form record-id={recordId} object-api-name="Account" layout-type="Full" columns="2" mode="edit"
       onsuccess={handleSuccess} onsubmit={handleSubmit}>
    </lightning-record-form>
</template>

update the recordform.js code as shown below.

import {
    LightningElement,
    api
} from 'lwc';

export default class Recordform extends LightningElement {
    @api recordId;
    handleSubmit(event) {
        console.log(event.detail);
    }
    handleSuccess(event) {
        console.log('Record iD' + event.detail.id);

    }
}

 

Use mode="view" and pass the ID of the record and the corresponding object API name to be displayed. Specify the fields using the fields attribute, or layout-type attribute to display all the fields defined on the Full or Compact layout.

 

the following code shows the how to edit the specific fields instead of layouts.update the recordform.html code as below.

<template>
    <lightning-record-form object-api-name={accountObject} record-id={recordId}  fields={myFields} mode="edit"
        onsuccess={handleSuccess} onsubmit={handleSubmit}>
    </lightning-record-form>
</template>

 

update the recordform.js code as shown below.

import {
    LightningElement,
    api
} from 'lwc';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import WEBSITE_FIELD from '@salesforce/schema/Account.Website';
export default class Recordform extends LightningElement {

    @api recordId ; 
     accountObject = ACCOUNT_OBJECT;
     myFields = [NAME_FIELD, WEBSITE_FIELD];
     
    handleSubmit(event) {
        console.log(event.detail);
    }
    handleSuccess(event) {
        console.log('Record iD' + event.detail.id);

    }
}

Now you can able to see the changes as shown below with the specified fields.

Viewing a Record Read-Only

The simplest way to display a record is to use the lightning-record-form. You can display a record in two modes.

view
Loads the form using output fields with inline editing enabled. Editable fields have edit icons. If a user clicks an edit icon, all fields in the form become editable, and the form displays Submit and Cancel buttons.
read-only
Read-only mode loads the form with output fields only. The form doesn’t include edit icons, Submit and Cancel buttons.

This code displays an account record in view mode using the compact layout, which includes fewer fields than the full layout.

Use mode="readonly" and pass the ID of the record and the corresponding object API name to be displayed. Specify the fields using the fields attribute, or layout-type attribute to display all the fields defined on the Full or Compact layout. The read-only mode loads the form with output fields only, and without Submit or Cancel buttons.The following code specifis how to use the read-only mode. Use the below recordform.html code.

<template>
    <lightning-record-form record-id={recordId} object-api-name="Account"
     layout-type="Full" columns="2" mode="readonly"
         onsuccess={handleSuccess} onsubmit={handleSubmit}>
    </lightning-record-form>
</template>

You can able to see the record with read-only data .

 

Let’s update the code with view mode as shown below. view Loads the form using output fields with inline editing enabled. Editable fields have edit icons. If a user clicks an edit icon, all fields in the form become editable, and the form displays Submit and Cancel buttons.

Update the code as shown below and you can able to see the edit icon

<template>
    <lightning-record-form record-id={recordId} object-api-name="Account" layout-type="Full"
     columns="2" mode="View"
        onsuccess={handleSuccess} onsubmit={handleSubmit}>
    </lightning-record-form>
</template>

 

 

Using Record types

If your org uses record types, picklist fields display values according to your record types. You must provide a record type ID using the record-type-id attribute if you have multiple record types on an object and you don’t have a default record type. Otherwise, the default record type ID is used. Display a record create a form based on a record type by providing the record-type-id attribute. This example shows a form that you can place on an account record page. The form displays fields, which include a picklist with values based on the given record type Id.

  <lightning-record-form object-api-name={objectApiName} 
                 record-type-id={recordTypeId}
                 fields={fields}>
            </lightning-record-form>

 

Error Message

To enable automatic error handling, include the component lightning-messages.To customize the behavior of your form when it loads or when data is submitted, use the onload and onsubmit attributes to specify event handlers. Errors are automatically handled. To customize the behavior of the form when it encounters an error on submission or when data is submitted successfully, use the onerror and onsuccess attributes to specify event handlers

<template>
            <lightning-messages></lightning-messages>

    <lightning-record-form record-id={recordId} object-api-name="Account" layout-type="Full"
     columns="2" mode="View"
        onsuccess={handleSuccess} onsubmit={handleSubmit}>
    </lightning-record-form>
</template>

 

 

How to Call SOAP Callouts In Lightning Web Components

Let’s discuss here how to use the soap API callouts form the lightning web components(lwc). Apex can also make callouts to SOAP web services using XML. Here we will be using the simple calculator WSDL from the trailhead. please refer to this link for WSDL 

 

Use WSDL2Apex to Generate Apex Code

Use WSDL2Apex to Generate the apex code from the WSDL.

  1. From Setup, enter Apex Classes in the Quick Find box, then click Apex Classes.
  2. Click Generate from WSDL.
  3. Click Choose File and select the downloaded calculator.xml file.
  4. Click Parse WSDL.

It will generate the apex class as shown below.C lick Generate Apex code. The final page of the wizard shows the generated classes, along with any errors.

 

 

Remote Site Settings 

You need to configure authorize endpoint in the remote site settings. Authorize endpoint URL of the web service callout is https://th-apex-soap-service.herokuapp.com&nbsp;

 

 

Create An Apex Class

Create an apex class with the below code. This class is calling SOAP callouts.

 

public with sharing class soapcallouts {

@AuraEnabled(cacheable=true)
public static Double getSum(Double val1 ,Double val2 ) {
        calculatorServices.CalculatorImplPort calculator =new calculatorServices.CalculatorImplPort();
        return   calculator.doAdd(val1,val2);
}
@AuraEnabled(cacheable=true)
public static Double getSub(Double val1 ,Double val2 ) {
        calculatorServices.CalculatorImplPort calculator =new calculatorServices.CalculatorImplPort();
        return   calculator.doSubtract(val1,val2);
}
@AuraEnabled(cacheable=true)
public static Double getMul(Double val1 ,Double val2 ) {
        calculatorServices.CalculatorImplPort calculator =new calculatorServices.CalculatorImplPort();
        return   calculator.doMultiply(val1,val2);
}


}

 

Create an LWC

 

Create an LWC using the below SFDX command

sfdx force:lightning:component:create --type lwc --componentname soapapiex --outputdir force-app\main\default\lwc

 

Use the below soapapiex.html code 

 

<template>
    <lightning-input type="number" label="Input 1" name="Input 1" onchange={handleChange}></lightning-input>
    <lightning-input type="number" label="Input 2" name="Input 2" onchange={handleChange}></lightning-input>

    <lightning-button variant="brand" label="+" title="Sum" onclick={handleSum} class="slds-m-left_x-small"></lightning-button>
    <lightning-button variant="brand" label="-" title="Sub" onclick={handleSub} class="slds-m-left_x-small"></lightning-button>
    <lightning-button variant="brand" label="*" title="Mul" onclick={handleMul} class="slds-m-left_x-small"></lightning-button>

    Result :- {result}

</template>

 

Use the below soapapiex.js code 

 

import {
    LightningElement,
    wire,
    api,
    track
} from 'lwc';
import getSum from '@salesforce/apex/soapcallouts.getSum';
import getSub from '@salesforce/apex/soapcallouts.getSub';
import getMul from '@salesforce/apex/soapcallouts.getMul';


export default class Soapapiex extends LightningElement {
    @track inp1 = 0;
    @track inp2 = 0;
    @track result = 0;
    @track error;

    handleChange(event) {
        console.log('label values --->>' + event.target.label);

        if (event.target.label === 'Input 1') {
            this.inp1 = event.target.value;
        }
        if (event.target.label === 'Input 2') {
            this.inp2 = event.target.value;
        }
    }

    handleSum(event) {
        getSum({
                val1: this.inp1,
                val2: this.inp2
            })
            .then(result => {
                this.result = result;
                this.error = undefined;
            })
            .catch(error => {
                this.error = error;
                this.result = undefined;
            });

    }
    handleSub(event) {
        getSub({
                val1: this.inp1,
                val2: this.inp2
            })
            .then(result => {
                this.result = result;
                this.error = undefined;
            })
            .catch(error => {
                this.error = error;
                this.result = undefined;
            });
    }

    handleMul(event) {
        getMul({
                val1: this.inp1,
                val2: this.inp2
            })
            .then(result => {
                this.result = result;
                this.error = undefined;
            })
            .catch(error => {
                this.error = error;
                this.result = undefined;
            });
    }

}

 

Use the below soapapiex.js-meta.xml code

 

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 

 

Push the changes to scratch org using the below command

sfdx force:source:push --forceoverwrite

 

You can able to see the calculator result as shown below.

Get Current User Details in Lightning Web Components

Let’s discuss here how to get the current user details in lightning web components. To access the current user Id, import @salesforce/user/Id in a component’s JavaScript class. Note that @salesforce/user/ cannot be imported by itself; you must indicate the property that you want to import. For the User standard object, only the Id field is available.

import Id from '@salesforce/user/Id';

 

Option 1: Using Wire Service

You can able to get the current user details using getRecord wire adapter and you can able to pass the user id from the imported modules. Create a new lightning web component using the below SFDX command

sfdx force:lightning:component:create --type lwc --componentname userinfoexample --outputdir force-app\main\default\lwc

Use the below userinfoexample.html code

<template>

        Name : {name}
        Email :{email}

</template>

Use the below userinfoexample.js code

 

import {
    LightningElement,
    wire,
    track
} from 'lwc';
import {
    getRecord
} from 'lightning/uiRecordApi';

import USER_ID from '@salesforce/user/Id';

import NAME_FIELD from '@salesforce/schema/User.Name';
import EMAIL_FIELD from '@salesforce/schema/User.Email';


export default class Userinfoexample extends LightningElement {
    @track error ;
    @track email ; 
    @track name;
    @wire(getRecord, {
        recordId: USER_ID,
        fields: [NAME_FIELD, EMAIL_FIELD]
    }) wireuser({
        error,
        data
    }) {
        if (error) {
           this.error = error ; 
        } else if (data) {
            this.email = data.fields.Email.value;
            this.name = data.fields.Name.value;
        }
    }

}

Use the below userinfoexample.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 

Push changes and you can able to see the user details

Option 2: – Using apex class

you can able to get the user detail even using the apex class .create an Apex class that returns the user details as shown below

 

public class UserInfoDetails {
@AuraEnabled(cacheable=true)
    public static User getUserDetails(String recId) {
        return  [Select Id , Name ,Email from User where Id =:recId];
    }
}

update the userinfoexample.html with below code

 

<template>
    <template if:true={user}>

        Name : {user.Name}
        EMail : {user.Email}
        Id : {user.Id}
    </template>

</template>

 

update userinfoexample.js code as shown below

import {
    LightningElement,
    wire,
    track
} from 'lwc';
import getUserDetails from '@salesforce/apex/UserInfoDetails.getUserDetails';
import Id from '@salesforce/user/Id';


export default class Userinfoexample extends LightningElement {
    userId = Id;
    @track user;
    @track error;
    @wire(getUserDetails, {
        recId: '$userId'
    })
    wiredUser({
        error,
        data
    }) {
        if (data) {
            this.user = data;

        } else if (error) {

            this.error = error;

        }
    }
}

Push changes and you can able to see the current logged in user details

 

Share JavaScript Code Between LWC and Aura

Let’s discuss here how to share the code between the lightning web component and Aura web components. To share JavaScript code between Lightning web components and Aura components, put the code in an ES6 module.

1. Create the ES6 module in your Lightning Web Components development environment.
2. Reference the module in a Lightning web component’s JavaScript file.
3. Reference the module in an Aura component.

Example – Create a Shared Code 

To share code between components, create an ES6 module and use the standard export statement to export the functionality that your module exposes. Your module can use the standard import statement to use other shared modules. Let’s create an ES6 module and see how it’s used in a Lightning web component. Create a folder for the utils module in the LWC folder in the lightning web component project directory. we will be using this utils code in between LWC and Aura Components.

cd force-app/main/default/lwc
mkdir utils
cd utils

The folder looks like below.

 

Create a utils.js file in the utils folder. This file is an ES6 module  that is export the isFunction

/* utils.js */
/**
* Returns whether provided value is a function
* @param {*} value - the value to be checked
* @return {boolean} true if the value is a function, false otherwise
*/
export function isFunction(value) {
return typeof value === 'function';
}

The utils module exports an isFunction() function that returns whether the provided parameter is a function.

Create a utils.js-meta.xml configuration file for the utils module.

 

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>45.0</apiVersion>
    <isExposed>false</isExposed>
</LightningComponentBundle>

 

Use Shared Code in LWC

Now you need to import the above create ES6 module utils .create a lightning web component using this command

 

 sfdx force:lightning:component:create --type lwc --componentname libcaller --outputdir force-app\main\default\lwc

Use this libcaller.html code.

<template>
    <p>LWC  Calling Shared Code </p>
    <p>Is it a function?: {result}</p>
    <button onclick={checkType}>Check Type</button>
</template>

Use this libcaller.js code

import { LightningElement ,api,track} from 'lwc';
// import the library
import {
    isFunction
} from 'c/utils';

export default class Libcaller extends LightningElement {
@track result;
checkType() {
    // call the imported library function
    this.result = isFunction(
        function () {
            console.log(" I am a function");
        }
    );
}
}

The c-libcaller component imports the utils module and calls the isFunction function exported by the module. The argument passed into isFunction is a function so the result is set to true. The below code shows how to import the utils code

import {
    isFunction
} from 'c/utils';

The above below code shows how to call the imported function

 isFunction(
        function () {
            console.log(" I am a function");
        }
    );

 

Use this libcaller.js-meta.xml code

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 

 

Push the changes to scratch org and add to layout for testing. When you click the Check Type button it will call then imported isFucntion module and set the value to the result property.

 

Use Shared Code in Aura 

Using the shared code in Aura is straight and you can able to call the module code like component and pass the aura:id

Create a libcallerAura.cmp .

The libcallerAura Aura component includes a reference to the c:utils ES6 module. We added an aura:id so that we can get a reference to the module in JavaScript code.

 

<aura:component implements="flexipage:availableForAllPageTypes">
    <p>Aura component calling the utils lib</p>
    
    <c:utils aura:id="utils" />
    <aura:attribute name="isfan" type="boolean" default="false"/>
    <lightning:button label="Click " title="Click" onclick="{! c.handleClick }"/>
    <p>
        Function or not ?: {!v.isfan}
    </p>
</aura:component>

Create a libcallerAuraController.js file.

({
    handleClick: function(cmp) {
        // Call the lib here
        var libCmp = cmp.find('utils');
        var result = libCmp.isFunction(
            function() {
                console.log(" I am a function");
            }
        );
        cmp.set("v.isfan" ,result);
        console.log("Is it a function?: " + result);
    }
})

 

 

The component’s controller uses cmp.find(‘utils’) to match the aura:id in markup and get a reference to the module. The utils ES6 module exports isFunction(), which the Aura component calls. The argument passed into isFunction is a function so result is set to true. Click the button and confirm that the Aura component calls the function exported by the ES6 module and set the attribute to true as shown below.

 

Lightning Web Component Slots

Let’s discuss here what is the slots in the lightning web component and those will be used to pass the properties from the parent component. A slot in a component’s HTML file is a placeholder for markup that a parent component passes into a component’s body. 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. Slots are part of the Web Component specification To define a slot in markup, use the <slot> tag, which has an optional name attribute. In an Aura component, a facet is a similar concept to a slot. Please refer to this link for facets 

We have two types of slots

  1. Unnamed slots
  2. Named slots

Unnamed Slots

An unnamed slot is a placeholder for any markup that a parent component passes into the body. For Example, in this component, we have defined the slot and parent component will pass the markup into this component.

 

 sfdx force:lightning:component:create --type lwc --componentname slotdemo --outputdir force-app\main\default\lwc

 

use this slotdemo.html code. This template markup is having the <slot> tag which will be used to pass the content from the parent component.

<template>
    <d6> Slot Base </d6>
    <h1>Add content to slot</h1>
    <div>
        <slot></slot>
    </div>
</template>

use the below slotdemo.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="slotdemo">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
</LightningComponentBundle>

 

create a parent component to pass the markup into the slots. use the below SFDX command.

 sfdx force:lightning:component:create --type lwc --componentname slotwrapper --outputdir force-app\main\default\lwc

Use the below slotwrapper.html code. When c-slot-wrapper is rendered, the unnamed slot is replaced with the markup passed into the body of c-slot-demo. Here’s the rendered output of c-slot-wrapper.

Use this slotwrapper.html code

<template>
    <h6>  Slot Wrapper </h6>
    <c-slotdemo>
        <p>content from parent</p>
    </c-slotdemo>
</template>

 

use the below slotwrapper.js-meta.xml code

 

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

When c-slot-wrapper is rendered, the unnamed slot is replaced with the markup passed into the body of.c-slot-demo .  Here’s the rendered output of c-slot-wrapper . If a component has more than one unnamed slot, the markup passed into the body of the component is inserted into all the unnamed slots. This UI pattern is unusual. A component usually has zero or one unnamed slot.

 

 

Named Slots

named slots are the slot with the name attribute. create a lightning web component using the below SFDX command.

 sfdx force:lightning:component:create --type lwc --componentname namedslots --outputdir force-app\main\default\lwc

 

Use the below namedslots.html code. This example component has two named slots and one unnamed slot.

 

<template>
    <p>First Name: <slot name="firstName">Default first name</slot>
    </p>
    <p>Last Name: <slot name="lastName">Default last name</slot>
    </p>
    <p>Description: <slot>Default description</slot>
    </p>
</template>

Update the soltwrapper.html code as shown below

 

<template>
    <c-namedslot>
        <span slot="firstName">Willy</span>
        <span slot="lastName">Wonka</span>
        <span>Chocolatier</span>
    </c-namedslot>
</template>

Push changes and now you can able to see the output as shown below

 

 

c-slotswrapper drops:

  •  “Willy” into the firstName slot
  •  “Wonka” into the lastName slot
  •  “Chocolatier” into the unnamed slotHere’s the rendered output.
    <p>First Name: <span slot=”firstName”>Willy</span></p>
    <p>Last Name: <span slot=”lastName”>Wonka</span></p>
    <p>Description: <span>Chocolatier</span></p>

 

DOM elements that are passed to a component via slots aren’t owned by the component and aren’t in the component’s shadow tree. To access these DOM elements passed in via slots, call this.querySelector() andthis.querySelectorAll(). The component doesn’t own these elements, so you don’t use this.template.querySelector() or this.template.querySelectorAll().

The following example shows how to get the DOM elements passed to a child component from the child’s context. Provide the selector name, such as an element, for this.querySelector() and this.querySelectorAll().

import { LightningElement } from 'lwc';

export default class Namedslot extends LightningElement {
    renderedCallback() {
        this.template.querySelector('div'); 
        this.template.querySelector('span'); 
       
    }

}