Aura Components
Published: 2021-06-20 06:37:18

*8 components in Aura Bundle.
*3js, 1css, 1svg, 1 cmp, 1doc, 
*TO run Bundle need App

Attributes name="xyz" value =1 replaces variables to show in front end
To show <attribute values -->{!v.xyz}
v signify Component (ie; visual value)
c signify controller (ie; Controller value)

For back end use .js controller

<aura:attribute> can be defined directly in application also because both are front end.
 Now we have 2 different ways to to to define aura:attribute 
1. Creating a lightning component and then calling it in the lightning application, 
2. lightning component attribute inside application


Button
<ui:button label="Click Me" press="{!c.myname}"/>

Js Controller = all functionality inside this.

**implements**
<aura:component implements="flexipage:availableForAllPageTypes" access="global"> : to make your component available for record pages and any other type of page,

**Calculator App**
Component=AddComponent.cmp
```
<aura:component >
    <aura:attribute name="num1" type="Integer" default="30"/>
    <aura:attribute name="num2" type="Integer" default="20"/>
    <aura:attribute name="sum" type="Integer" />
      {!v.num1} + {!v.num2} = {!v.sum}
   <br></br>
  <ui:button label= "Press Me" press="{!c.add}"/>
</aura:component>
```
Js.Controller =AddComponent.js 
```
({
 add : function(component) {
       var xyz = component.get("v.num1") + component.get("v.num2");
        component.set("v.sum",xyz);
                                              }
})
```

Output:![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9xpdxrancob8hm0dnc0g.png)
 
You can only use {!} Syntax in markup languages like HTML, hence in .app and .cmp  we are using {!} for expression.

<h4>ifElse</h4>
```
<aura:component>
  <aura:attribute name="edit"
                             type="Boolean"
                             default="True"/>
   <aura:if isTrue="{!v.edit}">
      <ui:button label="submit"/>
       <aura:set attribute="else">
          Hello, Welcome to SalesfrceKid Platform
     </aura:set>
   </aura:if>
</aura:component>
```
Output
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8dgu2l75f77t5b615ioy.png)
 
<h4>Value Providers</h4>
Value providers encapsulate related value together, similar to how an object encapsulates properties and methods.
The value providers for a component are v(view) and c(controller).
A component's view refers to its attribute set.
A component's controller enables you to wire up event handlers and action for the components. It's where you control your component's logic.

<h5>Global Value Providers /h5>
Here are some global value providers you need to know :

globalId: It returns the global ID for a component has a unique globalId, which is generated runtime-unique ID of the component instance.
$Browser: It returns information about the hardware and operating system of the browser accessing the application.
$Label: It enables you to access labels stored outside your code.
.
.
.
.
etc

```
<aura:component>
  Browser running on Tablet: {!$Browser.isTablet}
   <br></br>
    Is it running on IPhone: {!$Browser.isIPhone}
    <br></br>
     Is it running on Android: {!$Browser.isAndroid}
     <br></br>
I am Running on : {!$Browser.FormFactor}
</aura:component>
```
output
Browser running on Tablet: false
Is it running on IPhone: false
Is it running on Android: false
I am Running on DESKTOP

<h4>Server Side Controller or Apex Class</h4>
**With Sharing**: To respect salesforce security to connect with client side controller
**Static and stateless methods**: Method don't care who is calling them
**@AuraEnabled**:to enable the client and server-side access to the method.
Example: Apex class (server side component).apxc
```
public with sharing class simpleController//with sharing to share
{
 @AuraEnabled //to enable access
 public static String serverEcho (String firstName) //static
 {
  return('Hello from the server'+ firstName); 
 }
}
```
<h6> component</h6>
```
<aura:component controller="simpleController"> //linking apex
  <aura:attribute name="firstName" 
                             type="string" 
                             default="salesforceKid"/>
<ui:button label ="callServer" press="{!c.echo}"/> //calling js
</aura:component>
```
<h6>JS controller (client side controller)</h6>
```
//This is not class. It is JSON object with map of name value pair. Having only action handlers.
In function (component, event, and helper—though you can name them differently)
({
 echo : function(cmp, event, helper) { //Action handler as func.
                                       //can have only 3 paramtr 
  var action = cmp.get("c.serverEcho");//linking serverside (ssc) 
                                   controller function serverEcho
        action.setParams({         //Sending parameter to SSC
            firstName : cmp.get("v.firstName")
        })
        action.setCallback(this, function(response){ //callback
            var state = response.getState(); //add to variable
            if(state === "SUCCESS")          //comparing
            {
                alert("This is from server ::"+ response.getReturnValue());      //gets the value returned from 
                                  the server.              
            }
            else if(state === "INCOMPLETE")
            {
                //do something 
            }
            else if(state === "ERROR")
            {
             var error = response.getError();
             if(error)
             {
                 console.log("error"+errors);
             }
            }
        });
          $A.enqueueAction(action);// $A.enqueueAction adds the 
                                 server-side action to the queue.
                                 All actions that are enqueued 
                           will run at the end of the event loop

 }
})
```
**Important:**
c. IN component  represent client side Component
c. in JS controller represent server side component (apex)
c: is the default namespace. It represents Aura component code you’ve added to your org.

**Lightning Application**
```
<aura:application extends="force:slds"> //for SLDS
    <c:serverSide/>
</aura:application>
```


**wrapper Class**: Reduce server call and get data at one call 
```
public class wrapperClassController {

 @AuraEnabled 
    public static wrapper method(){
    //Get Required Account And Contact List by SOQL STEP 2
        List<Account> getAccount = [Select Id, Name  FROM Account];
        List<Contact> getContact = [Select Id, Name FROM Contact];    
//Instance before adding a list STEP 3
        wrapper wrp = new wrapper();
        wrp.accList = new List<Account>(getAccount);
        wrp.conList = new List<Contact> (getContact);
        return wrp;
    }

//Main Wrapper Class STEP 1
    public class wrapper{
       @AuraEnabled //Annotation when using for lightning component
          public List<Account> accList;
       @AuraEnabled 
          public List<Contact> conList;
    }   
}
```

**Init**
//doInIt Handler To call the c.doInIt action when screen load
   <aura:handler name="init" value="{!this}" action="{!c.abc}"/>
//abc is funtion name on CSC.(client side controller)

<h4>Events in Aura</h4>
<h6>component composition </h6>
communicate from parent component to child component, we include child component inside the parent component. 

<h6> Parent To Child</h6>

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ohqpoxufaayo37gizejm.png)

example: parentComponent.cmp
```
<aura:component>
<aura:attribute name="valueToChild" 
                          value="String">
<h6>This is parent component</h6>
//Including child component in parent 
<c:childComponent value="{v.valueToChild}"/>
</aura:component> 
```
Parent To Child Component Communication : 
In parent to child component communication, we can communicate by passing value from parent to child as explained above example. 
But when we want to communicate from Child To Parent we cannot directly pass value inside an attribute. In that case, we use lightning Events ⚡️

<h6> Event for Child to parent</h6>
1)Component Event
2) Application Event

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0bd7xbo1plxrkklcnnwf.png)

**1)Component Event**
Component Event On child-->Register it on Childcmp-->fire Event from Child Js-->use parent JS to handle Event--> pass value to parent cmp to use.

**lightning Tag vs UI tag**
UI tag was initially introduced
lightning tag has inbuilt SLDS we do not need to put extra effort to improve the look and feel, also it has may awesome tags to handle the Error or bad inputs.  

[Link](https://www.sfdckid.com//2020/02/component-events-in-salesforce-lightning.html)

[Link](https://developer.salesforce.com/blogs/developer-relations/2017/04/lightning-inter-component-communication-patterns.html)