Monday, 8 October 2018

Inheritance In Lightning Component


 Lightning framework Support inheritance same like Apex or Java. If you mark any component as extensible=”true” means component can be inherited by any component. Inheritance allows us use JavaScript functions and attributes of extensible component in child components.

We need to Follow below point
  1. Create a Base Component and set extensible=”true”.
  2. Create a controller or helper for base component.
  3. In Child Component set extend base component. Like extends=”C:BaseComponent”
  4. You can also use the Base Component attribute in Child Component like {!v.AttributeName }
  5. You can call Base component helper/controller method from child component like  helper.baseComponentHelperMethodName(params);
Use Case :- Some time we have many components which call apex controller method from helper function. So instead of writing getDataFromServer method in all components helper function , we  can create a component and mark it as extensible=”true” component and write getDataFromServer function in helper function once. Now in other components, we need to extends that component and we just need to call getDataFromServer function.

Here is Sample Code for you

Step 1) Create a Base Component and set extensible=”true”.

BaseComponent.cmp
<aura:component extensible="true" controller="AccountUtil" > 
    <aura:attribute name="message" type="String" default="Value from Parent"/>
    {!v.body}
</aura:component>

Step 2) Create a controller or helper for base component.

BaseComponentHelper.js
({
    getDataFromServer : function(component, method, callback, params )
    {
        var action = component.get(method);
        if (params) {
            action.setParams(params);
        }
        action.setCallback(this,function(response)
        {
            var state = response.getState();
            if (state === "SUCCESS") {
                callback.call(this,response.getReturnValue());  
            } else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    alert('errors'+errors);   
                }
            }
        });
        $A.enqueueAction(action);
    },
})

Step 3) In Child Component set extend base component. Like extends=”c:BaseComponent”

ChildComponent.cmp
<aura:component implements="flexipage:availableForAllPageTypes" extends="c:BaseComponent"  access="global" >
        <!-- This Example is for Inherit Component attribute-->
        <BR></BR>
            <div>
                <!--
                    Set Vaule if you want to override message value
                    <aura:set attribute="message" value="ChildComponent is inherited in BaseComponent"/>
                -->
                Inherited Component attribute Value =  {!v.message}
            </div>
        <BR></BR>
   
        <!-- This Example is for Inherit Helper method-->
        <aura:attribute name="ListAcc" type="List"/>
        <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
        <div class="slds-align--absolute-center">
            <table aura:id="accTable" class="slds-table slds-table--bordered slds-table--cell-buffer" cellspacing="0" width="100%">

                <thead>
                    <tr class="slds-text-title--caps">
                        <th scope="col">Account ID</th>
                        <th scope="col">Account name</th>
                        <th scope="col">Account Number</th>
                    </tr>
                </thead>   
                <tbody>
                    <aura:iteration items="{!v.ListAcc}" var="acc">
                        <tr>
                            <td>{!acc.Id}</td>
                            <td>{!acc.Name}</td>
                            <td>{!acc.AccountNumber}</td>
                        </tr>
                    </aura:iteration>
                </tbody>
            </table>
        </div>          
</aura:component>
 NOTE:- You can also use the Base Component attribute in Child Component like {!v.message }


ChildComponentController.js
({
    doInit : function(component, event, helper) {       
        helper.getAllAccounts(component, helper);
    },
})

Step 4) You can call Base component helper/controller method from child component like  helper.getDataFromServer(params);

ChildComponentHelper.js
({
    getAllAccounts : function(component, helper) {
        //Calling base component's helper method
        helper.getDataFromServer(component,
                                 "c.getAccounts",
                                 function(response){
                                     if(response){
                                         component.set("v.ListAcc", response);
                                     }
                                 }
                                );
    },
})


AccountUtil.apxc
public class AccountUtil {
   
    @AuraEnabled
    public static List<Account> getAccounts()
    {
        return [SELECT Id, Name, Phone, AccountNumber FROM Account  LIMIT 10];
    }
}


TestInheritance.app
<aura:application extends="force:slds">
    <c:ChildComponent />
</aura:application>


 Output:-


 
Please check our old post on Lightning :-
 
1) Invoke Apex from Lightning Component 

2) Design Resource In Lightning Component Bundle
3) Component Event in Lightning Component | aura:event
4) Modal/Popup in Lightning Component

5) Dynamically Creating Components Part 1:- createComponents

Feel free to post your feedback or question.


Thanks,
Amit Chaudhary

Capture.JPG  @amit_sfdc    @ApexHours
  Salesforce Apex Hours
    #SalesforceApexHours  

4 comments:

  1. Hi Amit,
    one info here i need .
    what is the use of {!v.body} in the base component

    Regards
    Ajay kumar

    ReplyDelete
    Replies
    1. Hi Ajay
      it's the body of the child component also know as slot
      Regards
      Arif

      Delete
  2. Hi Amit,
    one info here i need .
    what is the use of {!v.body} in the base component

    Regards
    Pradeep Joshi

    ReplyDelete
  3. How do you access the .app file?

    ReplyDelete