Basic Calculator program with static variables in Lightning Component

By | October 30, 2019

Lightning Component

<aura:handler name='init' value='{!this}' action="{!c.initFunction}" />

<lightning:button label="Add" onclick="{!c.invoke}" />
<lightning:button label="Sub" onclick="{!c.invoke}" />
<lightning:button label="Cancel" onclick="{!c.invoke}" />

<div>
    A Value = {!v.aval} <br/>
    B Value = {!v.bval} <br/>
    Result  = {!v.cval} 
</div>

Js Controller

({
	initFunction : function(component, event, helper) {        
        component.set('v.aval', 10);
        component.set('v.bval', 5);
        component.set('v.cval', 0);		
	},
    
    invoke : function(component, event, helper) {
        var source = event.getSource();
        var label = source.get('v.label');
        
        var a = component.get('v.aval');
        var b = component.get('v.bval');
        var c = component.get('v.cval');
        
        if(label=='Add'){
            c = a+b;
            component.set('v.cval',c);
        }
        else if(label=='Sub'){
            c = a-b;
            component.set('v.cval',c);
        }
        else if(label=='Cancel'){            
            component.set('v.cval',0);
        }
    }
    
})

Application

<aura:application extends="force:slds">
    <c:Calculator />
</aura:application>

Output

Initial screen
On click of add

Leave a Reply

Your email address will not be published. Required fields are marked *