Thursday, May 24, 2018

How to call Lightning Component from Visualforce page.

Scenario: Suppose we have a lightning component named as "xyz.cmp" with some attributes. Now we want to call this component from a VF page (CallLightingCompFromVF).

Solution:

  • First we have to create a component (xyz.cmp) with attributes let say "var1" and "var2" and these attributes have default value as "Mr." , "Mark" respectively.
<aura:component >
 <aura:attribute name="var1" type="String" default="Mr."/>
    <aura:attribute name="var2" type="String" default="Mark"/>
    Helo! {!v.var1} {!v.var2}
</aura:component>

          Now if we preview this component then, it will display "Hello! Mr.Mark" as an output.

  • Now create a lightning app called as dependency app where component (which need to be called from VF for our case xyz.cmp) dependency will be defined.

<!-- Extending from ltng:outApp adds SLDS resources to the page to allow your 
Lightning components to be styled with the Salesforce Lightning Design System (SLDS). 
If you don’t want SLDS resources added to the page, extend from ltng:outAppUnstyled 
instead. -->
<aura:application access="GLOBAL" extends="ltng:outApp">
    <aura:dependency resource="c:xyz"/>
</aura:application>

  • Now our aim is to call the above component from a VF page and pass different attribute's value. Let say after preview the VF (which call the above component) display or output will be "Hello! Ms.Andi
<apex:page >
    <!-- The below tag help to add lighting component to Visualforce page -->
    <apex:includeLightning />
    
    <!-- Declear a div where your lightning component will be displayed -->
    <div id="lightningDivId" />
    
    <!-- Script logic to call Lightning component from VF using a dependiecy app. -->
    <script>
        $Lightning.use("c:LigDependencyAppForVF", function() {
             $Lightning.createComponent("c:xyz",
                                           {var1 : "Ms.",
                                            var2 : "Andi"},
                                           "lightningDivId"
                                       );
            }
        );
    </script>
</apex:page>


LWC to LWC Communication using Lightning Messaging Service (Part - 2)

In my previous post ( previous post link ) we have learn how to create a Lightning Messaging Service with 6 steps and today we will use the ...