Lightning Web Component Methods

Let us Discuss here how to use the Lightning Web Component Methods. Use a JavaScript method to communicate down the containment hierarchy. For example, a parent component calls a method on a child component that it contains. Methods are part of a component’s API. Expose a method by adding the @api decorator to the method. To communicate up the containment hierarchy, fire an event in the child component with the dispatchEvent method, and handle it in the parent component. Please refer this link to Aura method 

1. Create a Lightning web Component

Create a lightning web component using the below SFDX command

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

This component contains one method that will convert the text into the upper cases. This example exposes changeUpperCase(), methods in a c-inputmethod component by adding the @api decorator to the methods. A parent component that contains c-inputmethod can call these methods.

Use the below inputmethod.html code

<template>
Upper Case : {upperCase} <br/>
</template>

Use the below inputmethod.js code

import {
    LightningElement,
    api,
    track
} from 'lwc';

export default class Inputmethod extends LightningElement {
    @track upperCase;
    @api
    changeUpperCase(text) {
        this.upperCase = text.toUpperCase();
    }
   
}

Use the below inputmethod.js-meta.xml code

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

 

 

Call a Method

Now let’s see how to call the above method in the code  The c-method caller component contains c-inputmethod that call the changeuppercase() method in input change.  The this.template.querySelector() call is useful to get access to a child component so that you can call a method on the component.

Return Values

Use the return statement to return a value from a JavaScript method

@api
    changeUpperCase(text) {
        return 'value'
    }

 

Method Parameters

To pass data to a JavaScript method, define one or more parameters for the method. For example, you could define the change()
method to take an input parameter.

@api change(inp) { … }

 

2. Create a Lightning Web Component

Create another that will be calling the method.

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

 

use the below methodcaller.html code

<template>
    <lightning-card title="Container Cmp">
        <lightning-layout>
            <lightning-layout-item flexibility="auto">
                <lightning-input label="Input Phrase" onchange={handleChange}></lightning-input><br />
            </lightning-layout-item>
            <lightning-layout-item flexibility="auto">
                <h3> Method Source</h3>
                <c-changecase></c-changecase>
            </lightning-layout-item>
        </lightning-layout>
    </lightning-card>
</template>

 

use the below methodcaller.js code

import {
    LightningElement
} from 'lwc';

export default class Methodcaller extends LightningElement {
    handleChange(event) {
        this.template.querySelector('c-changecase').changeUpperCase(event.target.value);

    }
}

Use the below methodcaller.js-meta.xml code

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

 

push the changes and add it to the page layout and you can able to see the output as shown below.

Using Custom Labels In Lightning Web Components

Let’s discuss here how to use the Custom labels in the lightning web components. Custom labels are text values stored in Salesforce that can be translated into any language that Salesforce supports. Use custom labels to create multilingual applications that present information (for example, help text or error messages) in a user’s native language. To create custom labels, from Setup, enter Custom Labels in the Quick Find box, then select Custom Labels. To import a label in a Lightning Web Component JavaScript file, use @salesforce/label in an import statement.

1.Create custom labels

To create custom labels, from Setup, enter Custom Labels in the Quick Find box, then select Custom Labels. Here are the custom labels created. we will see how to use the lightning web components

 

 

2. Use Custom Labels in LWC 

To import a label in a Lightning Web Component JavaScript file, use @salesforce/label in an import statement.

import labelName from '@salesforce/label/label-reference';

The label-reference is the label name and must include a namespace in the format namespace.labelName.create a lightning web component using the following SFDX command

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

 

Use the below labelexamples.html.To use the labels in the template, use the same {property} syntax that you use to reference any JavaScript property.

<template>
    <lightning-card title={label.title}>
        <lightning-button label={label.save}></lightning-button>
        <lightning-button label={label.edit}></lightning-button>

    </lightning-card>
</template>

 

Use the below labelexamples.js code.

 

import { LightningElement } from 'lwc';
import edit from '@salesforce/label/c.Edit';
import save from '@salesforce/label/c.Save';
import title from '@salesforce/label/c.Title';

export default class Labelexamples extends LightningElement {
     label = {
         edit,
         title,
         save
     };
}

 

Use the below labelexamples.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 add this component to the page layout and you can able to see labels are coming from the custom label as shown below

 

Using Lightning Components In Visualforce page

In this blog, I am going to explain how to invoke the lightning component from the visualforce page by using Lightning out. Add Lightning components to your Visualforce pages to combine features you’ve built using both solutions. Implement new functionality using Lightning components and then use it with existing Visualforce pages. Lightning Components for Visualforce is based on Lightning Out, a powerful and flexible feature that lets you embed Lightning components into almost any web page.

Step 1: Create Sample Component

Create a lightning component with below code which contains two attributes

<aura:component access="global">
    <aura:attribute name="greeting" type="String" default="Hello" access="global" />
    <aura:attribute name="subject" type="String" default="World" access="global" />
    <div style="box">
        <span class="greeting">{!v.greeting}</span>, {!v.subject}!
    </div>
    
</aura:component>

Step 2: Create  Lightning Dependency App

To use Lightning Components for Visualforce, define component dependencies by referencing a Lightning dependency app. This app is globally accessible and extends ltng:outApp. The app declares dependencies on any Lightning definitions (like components) that it uses.

<aura:application access="GLOBAL" extends="ltng:outApp">
    <aura:dependency resource="c:helloworld"/>   
</aura:application>

Step 3: Using in Visualforce from the page

There are three steps to add Lightning components to a Visualforce page.

  1. Add the Lightning Components for Visualforce JavaScript library to your Visualforce page using the <apex:includeLightning/>  component.
    <apex:includeLightning/>
  2. To reference this app on your page, use the following JavaScript code.
    $Lightning.use("theNamespace:lcvfTest", function() {});
    
  3. Finally, add your top-level component to a page using $Lightning.createComponent(String type, Object attributes, String locator, function callback). This function is similar to $A.createComponent(), but includes an additional parameter, domLocator, which specifies the DOM element where you want the component inserted.

Here is the final code.

<apex:page docType="html-5.0" standardStylesheets="false" >
    <apex:includeLightning />
    
    <div id="lightning" />
    
    <script>
    $Lightning.use("c:helloworldApp", function() {
        $Lightning.createComponent("c:helloworld",
                                   {
                                       "greeting" : "Hello" ,
                                       "subject" : "World!" 
                                   },
                                   "lightning",
                                   function(cmp) {
                                       // do some stuff
                                   });
    });
    </script>
</apex:page>

 

 

lightning:utilityBarAPI Example

This component allows you to access methods for programmatically controlling a utility within the utility bar of a Lightning app. The utility bar is a footer that gives users quick access to frequently used tools and components. Each utility is a single-column Lightning page that includes a standard or custom Lightning component.

To access the methods, create an instance of the lightning:utilityBarAPI component inside of your utility and assign an aura:id attribute to it.

<lightning:utilityBarAPI aura:id="utilitybar"/>

Here is the lightning component

<aura:component implements="flexipage:availableForAllPageTypes" access="global" >
    <lightning:utilityBarAPI aura:id="UtilityBarEx" />
    <lightning:button label="set Utility Label" onclick="{! c.setUtilityLabel }" />
    <lightning:button label="Set Utility Icon" onclick="{! c.setUtilityIcon }" />
    <lightning:button label="set Utility Highlighted" onclick="{! c.setUtilityHighlighted }" />
    
    <lightning:button label="set Panel Height" onclick="{! c.setPanelHeight }" />
    <lightning:button label="set Panel Width" onclick="{! c.setPanelWidth}" />
    
    
    <lightning:button label="set PanelHeader Label" onclick="{! c.setPanelHeaderLabel }" />
    <lightning:button label="set PanelHeader Icon" onclick="{! c.setPanelHeaderIcon }" />
    
    
</aura:component>

 

({
    setUtilityIcon : function(component, event, helper) {
        var utilityAPI = component.find("UtilityBarEx");
        utilityAPI.setUtilityIcon({icon: 'insert_tag_field'});
    },
    setUtilityLabel: function(component, event, helper) {
        var utilityAPI = component.find("UtilityBarEx");
        utilityAPI.setUtilityLabel({label: 'Salesforce Utility '});
    },
    setUtilityHighlighted :  function(component, event, helper) {
        var utilityAPI = component.find("UtilityBarEx");
        utilityAPI.setUtilityHighlighted({highlighted:true});
    },
    
    
    setPanelWidth:function(component, event, helper) {
        var utilityAPI = component.find("UtilityBarEx");
        utilityAPI.setPanelWidth({widthPX:120});
    },
    
    setPanelHeight:function(component, event, helper) {
        var utilityAPI = component.find("UtilityBarEx");
        utilityAPI.setPanelHeight({heightPX :120});
    },
    
    setPanelHeaderLabel :function(component, event, helper) {
        var utilityAPI = component.find("UtilityBarEx");
        utilityAPI.setPanelHeaderLabel({label  :'Panel Header'});
    },
    
    setPanelHeaderIcon : function(component, event, helper) {
        var utilityAPI = component.find("UtilityBarEx");
        utilityAPI.setPanelHeaderIcon({icon: 'insert_tag_field'});
    },
})

Add Component to lightning App Utility Bar items

You can see Utility bar as shown below

On click on Set Utility highlighted which  Makes a utility more prominent by giving it a different background color as shown below