The below code shows how to use Ternary Operator in Salesforce Lightning Components:
Ternary_Operator.cmp
<aura:component > <aura:attribute name=”isError” type=”Boolean” description=”If Name is empty then true, else false”/> <aura:handler name=”init” value=”{!this}” action=”{!c.doInit}” /> <div class=”init”> <lightning:input label=”Enter your Name” aura_id=”FullName” class=”{!v.isError == true ? ‘error errorBorder’ : ‘correct correctBorder’}” onchange=”{!c.handleNameChange}” /> </div> </aura:component>
Ternary_Operator.js
({ doInit: function(component) { component.set(“v.isError”,true); }, handleNameChange : function(component){ var name = component.find(“FullName”).get(“v.value”); if(name == null || name == ” || name == undefined){ component.set(“v.isError”,true); } else{ component.set(“v.isError”,false); } }, })
Ternary_Operator.css
.THIS {} .THIS .error{ background-color:#D25A5A;} .THIS .correct{ background-color:#a3ea82;} .THIS .errorBorder{ border-color: red; border-width: 10px; border-style: solid;} .THIS .correctBorder{ border-color: green; border-width: 10px; border-style: solid; } .THIS.init{ width:50%; position:relative; left:200px; top:100px; }
Ternary_OperatorApp.app
<aura:application extends=”force:slds”> <c:Ternary_Operator/></aura:application>
Happy Salesforce Coding!
Leave a comment