Aura Components Basics

Before You Start

Determine if you have the skills to complete this module. Create a required custom object. Configure your org for Lightning components development.
  • Before You Start This Module
    • My Domain is required to develop with Lightning components
    • The Expense custom object described below is required for this module
  • My Domain Is Already On in Your Trailhead Playground
    • My Domain is already turned on in every Trailhead Playground
    • My Domain lets you create a subdomain unique to your organization, so that it shows up as something company-specific, like https://mydomainname.my.salesforce.com instead of including the Salesforce instance, like https://na17.salesforce.com
    • My Domain is required to create custom Lightning components and set up Single Sign-On (SSO) in an org - all production, Developer Edition, and trial orgs created Winter ‘21 or later get My Domain by default
  • Define the Expense Custom Object
    • Custom Object: Expense
    • Custom Fields: Amount (number), Client (text), Date (date), Reimbursed (checkbox)
  • Skills You Need to Complete This Module
    • Lightning component framework requires code, so to complete this module:
      • Should be comfortable reading and writing JavaScript
        • Salesforce recommends getting started learning JavaScript with [http://jstherightway.org/](JavaScript The Right Way)
      • Should know Apex, which is how you ready and write data from Salesforce
        • You can pass the module without know too much Apex, but real apps require writing plenty of Apex
        • Salesforce recommends the Apex Basics & Database module to learn Apex
      • If coming to Lightning components from Visualforce, eventually complete the Apply Visualforce Skills to Lightning Components
    • Passing the module without those skills is possible but may be frustrating
    • Without those skills you “won’t really be ready to uses Lightning components to write apps”

  • Custom Object: Camping Item
  • Custom Fields: Quantity (Number, required), Price (Currency required), Packed (Checkbox)

Get Started with Aura Components

Describe what the Lightning Components framework is, and what it’s used for. List four key differences between Lightning Components and other web app frameworks. List at least five different ways you can use Lightning Components to customize Salesforce.
  • Getting Started with Lightning Components
    • The Lightning Components framework is the “most exciting and powerful app development technology we’ve built in years”
    • The Salesforce app and Lightning Experience were built with it
  • What Is the Lightning Component Framework?
    • “The Lightning Component framework is a UI framework for developing web apps for mobile and desktop devices”
      • Modern framework for building single-page applications with dynamic, responsive user interfaces for Lightning Platform apps
        • An app framework is a collection of code and services that makes it easier to create your own custom apps, without having to write all the code
        • Other examples: Ruby on Rails, Grails, AngularJS, Django, CakePHP, etc
        • Web apps have evolved from simple, page-by-page oriented experiences to highly responsive apps that have all the same behavior and interactivity of native apps, on desktops and especially mobile devices
          • Runs from a single URL and then continuously as you use it
          • Plumbing is handled by a framework, like Lightning Component framework
      • Uses JavaScript on the client side, Apex on the server side

An Example Aura Component

<aura:component>
    <aura:attribute name="expense" type="Expense__c"/>
    <aura:registerEvent name="updateExpense" type="c:expensesItemUpdate"/>
    <!-- Color the item green if the expense is reimbursed -->
    <lightning:card title="{!v.expense.Name}" iconName="standard:scan_card"
                    class="{!v.expense.Reimbursed__c ?
                           'slds-theme_success' : ''}">
        <aura:set attribute="footer">
            <p>Date: <lightning:formattedDateTime value="{!v.formatdate}"/></p>
            <p class="slds-text-title"><lightning:relativeDateTime value="{!v.formatdate}"/></p>
        </aura:set>
        <p class="slds-text-heading_medium slds-p-horizontal_small">
            Amount: <lightning:formattedNumber value="{!v.expense.Amount__c}" style="currency"/>
        </p>
        <p class="slds-p-horizontal_small">
           Client: {!v.expense.Client__c}
        </p>
        <p>
            <lightning:input type="toggle"
                             label="Reimbursed?"
                             name="reimbursed"
                             class="slds-p-around_small"
                             checked="{!v.expense.Reimbursed__c}"
                             messageToggleActive="Yes"
                             messageToggleInactive="No"
                             onchange="{!c.clickReimbursed}"/>
        </p>
    </lightning:card>
</aura:component>
  • Code above is XML, including static HTML and custom Aura component tags
    • <aura:component>: starts off the sample
    • <lightning:card>: creates a container around a group of info
    • <lightning:formattedDateTime>: displays formatted date and time
    • <lightning:relativeDateTime>: displays the relative time difference between current time and provided time
    • onchange="{!c.clickReimbursed}: attribute on toggle switch, that’s really a fancy checkbox that slides right and left to represent checked and unchecked values. Says “When changed, call the controller’s clickReimbursed function.”
({
    clickReimbursed: function(component, event, helper) {
        let expense = component.get("v.expense");
        let updateEvent = component.getEvent("updateExpense");
        updateEvent.setParams({ "expense": expense });
        updateEvent.fire();
    }
})
  • Code above is the component’s client-side controller, written in JavaScript
    • In Aura Component programming model, components are bundles of code:
      • Includes markup like the earlier sample, in the “.cmp resource”
      • Can include JavaScript code, in a number of associated resources
  • What About Visualforce?
    • Visualforce and Lightning Components have different strengths
      • Visualforce isn’t going away, and existing apps don’t need to be converted
      • Lightning Components are optimzied to perform well on mobile, but Visualforce is not
      • More specifics are covered in the Develop for Lightning Experience module
  • What About AngularJS, React, and Those Other JavaScript Frameworks?
    • Salesforce says these frameworks are a great way to build Lightning Platform apps
      • Recommended to use them with Visualforce, using a “container page,” and package your chosen framework and app code into static resources
    • Third-party JavaScript frameworks + Lightning components may be a bit cumbersome
      • Lightning Component framework and most modern frameworks overlap quite a bit in features, so best to use Lightning Components, which are quicker to develop with
  • Where You Can Use Lightning Components
    • Can create apps hosted on Salesforce or hosted on other platforms, including embedding them into apps from those platforms
  • Add Apps to the Lightning Experience App Launcher
    • The App Launcher contains any custom apps you have created

  • Add Apps to Lightning Experience and Salesforce App Navigation
    • You can also add them as tabs in other apps

  • Create Drag-and-Drop Components for Lightning App Builder and Experience Builder
    • Lightning components can be added to pages using Lightning App Builder and Experience Builder

  • Add Lightning Components to Lightning Pages
    • Lightning components can be added to pages using Lightning App Builder and Experience Builder
  • Add Lightning Components to Lightning Experience Record Pages
    • Lightning components can be added to pages using Lightning App Builder and Experience Builder

  • Launch a Lightning Component as a Quick Action
    • Create actions using a Lightning component, and add the action to an object’s page layout to make it accessible

  • Override Standard Actions with Lightning Components
    • Closely parallels overriding an action with a Visualforce page

  • Create Stand-Alone Apps
    • These can be used independently from the standard Salesforce environment

  • Run Lightning Components Apps Inside Visualforce Pages
    • Add Lightning components to Visualforce pages to combine features built using both solutions
  • Run Lightning Components Apps on Other Platforms with Lightning Out
    • Extends Lightning apps, acting as a bridge to surface Lightning components in any remote web container, so you can use your Lightning components inside of an external site like Sharepoint or SAP
  • Customize Flow Screens
    • With a custom Lightning component, you can fully customize the look-and-feel and functionality of a screen flow



  • Lightning Components framework:
    • Is a UI framework for developing web apps for mobile and desktop devices
    • Uses JavaScript on the client side and Apex on the server side
    • Is a modern framework for building single-page applications
  • With the Lightning Component framework, you can build:
    • Standalone apps
    • Components to use inside Visualforce pages
    • Drag-and-drop components for Lightning App Builder
  • Lightning component framework is different from other web app frameworks in that:
    • It is optimized for both mobile and desktop experiences and proves it with Salesforce1 and Lightning Experience
    • It connects natively with services provided by the Salesforce platform
    • It has specific opinions about how data access is performed and has specific security requirements

Create and Edit Aura Components

Create and edit Aura component bundle resources in the Developer Console. Create a “harness” application for testing components in development. Perform the edit and reload cycle for previewing components in development. List the different resources that make up an Aura component bundle.
  • Creating and Editing Aura Components
    • Can write Aura components from the Developer console
  • Create Aura Components in the Developer Console
    • Create a new Aura component via: File > New > Lightning Component, for this example called helloWorld
    • The component that is generated contains the opening and closing tags for an Aura component: <aura:component ></aura:component>
    • For this example, add <p>Hello Lightning!</p> to the markup between the Aura application tags
    • To view an Aura component, you need to run the component inside a container app, called a “container”
      • Example containers: “Lightning Experience” or “Salesforce apps”, an app you build with Lightning App Builder, or any of the things described at the end of the “Get Started with Aura Components” section
      • For now, will create a simple “harnessApp” to display it
  • Create a “harnessApp":
    1. File > New > Lightning Application
    2. Name it “harnessApp”
    3. Add <c:helloWorld/> to the component markup, so it shows up as shown below. This adds the helloWorld app to the harnessApp app. Now a “Preview” button shows up in the app.
    4. Saving and clicking “Preview” will open a tab containing the helloWorld Aura app code

    • File > Open > Lightning Resources lets you open a bunch of Lightning resources all at once
    • Note that the URL for the preview is the permanent home of the app, which comes with the format
      https://MyDomainName.lightning.force.com/Namespace/AppName.app
      In trailhead orgs, the c represents the default namespace

helloWorld:

<aura:application >
	<p>Hello Lightning!</p>
</aura:application>

harnessApp:

<aura:application >
	<c:helloWorld/>
</aura:application>

  • What Is a Component?
    • Components are bundles that include a definition resource, written in markup, and may include other resources such as a controller, stylesheet, etc
      • Resources are like files, but stored in Salesforce
    • Bundles are sort of like folders - they group the related resources for a single component. The resources are auto-wired (hooked up) automatically.
    • Clicking the Style button in developer console opens a new tab for the style resource that was added to the bundle
    • The THIS keyword is the scoping string named for your component
    • Clicking the CONTROLLER and HELPER items adds those resources to the bundle. Then, the bundle looks like the following:
      • helloWorld: component bundle
        • helloWorld.cmp: component’s definition
        • helloWorldController.js: the component’s controller, or main JavaScript file
        • helloWorldHelper.js: the component’s helper, or secondary JavaScript file
        • helloWorld.css: the component’s styles
.THIS {
}
p.THIS {
    font-size: 24px;
}
  • What Is an App?
    • apps are a special components - they are different from a component in two meaningful ways:
      • An app uses <aura:application> tags instead of <aura:component> tags
      • Only an app has a Preview button in Developer console
  • What Are Apps For?
    • Practical differences between Apps and Components:
      • You can add a component to an app, but cannot add an app to another app, and cannot add an app to a component
      • An app has a standalone URL you can access while testing that you can publish to your users - these are often called “my.app”
      • Can’t add apps to Lightning Experience or Salesforce app, only components
    • So, usually you build all your “app” functionality inside a top-level component, then add that component to another container
    • In the real world, creating an Aura app means building functionality inside a component bundle, not an application bundle
  • Components, Containing Components, Containing… Components!
    • Composition: Common design pattern is to keep nesting components inside each other, starting with simple, “fine-grained” components then assembling those components upward into new components with higher-level functionality

harnessApp:

<aura:application >
	<c:helloWorld/>
</aura:application>

helloWorld

<aura:component >
    <c:helloHeading/>
	<p>Hello Lightning!</p>
</aura:component>

helloHeading

<aura:component>
    <h1>W E L C O M E</h1>
</aura:component>



harnessApp:

<aura:application >
	<c:camping/>
</aura:application>

camping:

<aura:component >
	<c:campingHeader/>
    <c:campingList/>
</aura:component>

campingHeader:

<aura:component >
	<h1>Camping List</h1>
</aura:component>

campingHeader.css:

.THIS {
    font-size: 18px;
}

campingList:

<aura:component >
	<ol>
    	<li>Bug Spray</li>
        <li>Bear Repellant</li>
        <li>Goat Food</li>
    </ol>
</aura:component>

Attributes and Expressions

Define attributes on your components, and pass attribute values into nested components. Understand the difference between a component definition and a component instance, and create multiple instances of a component. Create basic expressions to display changing and calculated values. Create conditional expressions for dynamic output.
  • Component Attributes
    • Attributes on components are like instance variables in objects - a way to save values that change and name those value placeholders
    • Attributes are defined using an <aura:attribute> tag
    • Attributes themselves have attributes
      • Required: name, type
      • Optional: default, description, required
<aura:component>
    <aura:attribute name="message" type="String"/>
    <p>Hello! {!v.message}</p>
</aura:component>
  • Expressions
    • In snippet above, contents of message are output using the expression {!v.message}
    • Expressions are essentially a formula, or calculation, you place within expression delimiters: {! and }
    • Expression values are any set of literal values, variables, sub-expressions, or operators that can be resolved to a single value
    • You can use operators inside expressions as well, as show below:
      {!$Label.c.Greeting + v.message}
    • Last, you can pass expressions to another component to set the value on that component. For example:
<aura:component>
    <aura:attribute name="customMessage" type="String"/>
    <p> <c:helloMessage message="{!v.customMessage}"/> </p>
</aura:component>
  • Value Providers
    • The v. part of the message above is called the value provider, a way to group, encapsulate, and access related data. They are a “hook” to access the component’s message attribute, which is how you access all of a component’s attributes.
    • When an attribute of a component is on an object, access the values using dot notation, for example {!v.account.Id}
  • Attribute Data Types
    • Various attribute types are available, including:
      • Primitives: Boolean, Date, Datetime, Decimal, Double, Integer, Long, String
      • Standard Objects and Custom Objects: Account MyCustomObject__c
      • Collections: List, Set, Map
      • Custom Apex Classes
      • Framework-specific types: Aura.Component or Aura.Component[] (not covered yet)
    • Component in the example below has one attribute, expense, a custom object
      • Purpose of component is to display the details of an expense by referencing the field on the Expense__c record using the {!v.expense.fieldName} expression
      • Note in example we’re using the <lightning:input> component of type="toggle"
<aura:component>
    <aura:attribute name="expense" type="Expense__c"/>
    <p>Amount:
        <lightning:formattedNumber value="{!v.expense.Amount__c}" style="currency"/>
    </p>
    <p>
        Client: {!v.expense.Client__c}
    </p>
    <p>
        <lightning:input type="toggle"
                         label="Reimbursed?"
                         name="reimbursed"
                         checked="{!v.expense.Reimbursed__c}" />
     </p>
    <!-- Other markup here -->
</aura:component>
  • Other Aspects of Attribute Definitions
    • default attribute: defines the default attribute value - used when the attribute is referenced and you haven’t set the attribute’s value yet
    • required: defines whether the attribute is required - default is false
    • description: defines a brief summary of the attribute and its usage
  • Fun with Attributes and Expressions
    • See example component, helloPlayground, below:
      • message is an attribute of helloPlayground that’s a complex data type
      • Accessing the third item will fail if someone creates a c:helloPlayground with only two messages
      • List Iteration section: shows a better way to work through all items in the list - <aura:iteration> component repeats its body once per item, so it can accommodate lists of variable lengths
      • Conditional Expressions and Global Value Providers section: shows a way to choose between two possible outputs
    • In object-oriented programming, there’s a difference between a class and an instance of that class. Components have a similar concept:
      • .cmp resource: definition of a class of a given component
      • When you put a component tag in a .cmp, you are creating a reference to (IE instance of) that component
      • Example below creates eight references to (instances of) the <c:helloMessage> component

harnessApp.app:

<aura:application >
	<c:helloPlayground/>
</aura:application>

helloPlayground.cmp:

<aura:component>
    <aura:attribute name="messages" type="List"
        default="['You look nice today.',
            'Great weather we\'re having.',
            'How are you?']"/>
    <h1>Hello Playground</h1>
    <p>Silly fun with attributes and expressions.</p>
    <h2>List Items</h2>
    <p><c:helloMessage message="{!v.messages[0]}"/></p>
    <p><c:helloMessage message="{!v.messages[1]}"/></p>
    <p><c:helloMessage message="{!v.messages[2]}"/></p>
    <h2>List Iteration</h2>
    <aura:iteration items="{!v.messages}" var="msg">
        <p><c:helloMessage message="{!msg}"/></p>
    </aura:iteration>
    <h2>Conditional Expressions and Global Value Providers</h2>
    <aura:if isTrue="{!$Browser.isIPhone}">
        <p><c:helloMessage message="{!v.messages[0]}"/></p>
    <aura:set attribute="else">
        <p><c:helloMessage message="{!v.messages[1]}"/></p>
        </aura:set>
    </aura:if>
</aura:component>

helloMessage.cmp:

<aura:component>
    <aura:attribute name="message" type="String"/>
    <p>Hello! {!v.message}</p>
</aura:component>

campingListItem.cmp:

<aura:component >
	<aura:attribute name="item" type="Camping_Item__c" required="True"/>
    <p>{!v.item.Name}</p>
    <p><lightning:formattedNumber value="{!v.item.Price__c }" style="currency"/></p>
    <p><lightning:formattedNumber value="{!v.item.Quantity__c }"/></p>
    <p><lightning:input type="toggle"
                        label="Packed?"
                        name="Packed"
                        checked="{!v.item.Packed__c}" /></p>
</aura:component>

Handle Actions with Controllers

Create a client-side controller to handle user actions. Read values from component attributes. Read values from user interface controls in your component. Write controller code in JavaScript that changes the user interface.
  • Handling Actions with Controllers
    • Sections above this one all involved working with XML-style markup only - the components’ output hasn’t changed based on user input - this section introduces JavaScript
    • In the sample code below,
<aura:component>
    <aura:attribute name="message" type="String"/>
    <p>Message of the day: {!v.message}</p>
    <div>
        <lightning:button label="You look nice today."
            onclick="{!c.handleClick}"/>
        <lightning:button label="Today is going to be a great day!"
            onclick="{!c.handleClick}"/>
    </div>
</aura:component>
  • Uh, What’s a Controller?
  • Beyond the Basics
  • Action Handlers
  • The Aura Components View-Controller Programming Model
  • Function Chaining, Rewiring, and Simple Debugging

Input Data Using Forms

Create a form to display current values and accept new user input. Read values from form elements. Validate user input and display error messages for invalid input. Refactor code from a component’s controller to its helper.
  • Input Data Using Forms
  • The expenses App Container
  • The expenses App Component
  • The New Expense Form
  • Attributes for Salesforce Objects (sObjects)
  • Handle Form Submission in an Action Handler
  • Create the New Expense
  • The Reference is Not the Collection
  • Displaying the List of Expenses

Connect to Salesforce with Server-Side Controllers

Create Apex methods that can be called remotely from Aura component code. Make calls from Aura components to remote methods. Handle server responses asynchronously using callback functions. Stretch goal: explain the difference between “c.”, “c:”, and “c.”.
  • Server-Side Controller Concepts
  • Querying for Data from Salesforce
  • Loading Data from Salesforce
  • Calling Server-Side Controller Methods
  • Server Calls, Asynchronous Execution, and Caallback Functions
  • Handling the Server Response
  • Apex Controllers for Aura Components
  • Saving Data to Salesforce
  • Things to Watch Out For

Connect Components with Events

Define custom events for your apps. Create and fire events from a component controller. Create action handlers to catch and handle events that other components send. Refactor a big component into smaller components.
  • Connect Components with Events
  • Composition and Decomposition
  • The Wiring-a-Circuit Metaphor, Yet Again
  • Sending an Event from a Component
  • Defining an Event
  • Sending an Event
  • Handling an Event
  • Refactor the Helper Functions
  • Refactor the Add Expense Form
  • Bonus Lesson-Minor Visual Improvements

Discover Next Steps

List five aspects of Aura components that you can explore in more depth. Plan three improvements you could make to the Expenses app. Earn. This. Badge!
  • Congratulations!
  • What We Skimmed Over or Zipped Past
  • What We Didn’t Cover At All
  • Exercises for the Adventurous