1.4 Use attributes to carry information

In lightning component and apps, we can use attributes to carry the information we need. In today’s example, I am gonna show you the basic usage of attributes in lightning components.

The code

Let’s update your HelloWorldCmp code into below code:

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

Then, let’s update HelloWorldApp code into below:

<aura:application>
    <aura:attribute name="customerName" type="String"/>
    <c:HelloWorldCmp customerName="{!v.customerName}"/>
</aura:application>

Now, run your app by navigating into this url: https://[YourDomainName].lightning.force.com/c/HelloWorldApp.app?customerName=Lance.

Change Lance into your own name. You will see Hello, [Your Name] displayed .

A little bit explanation

If you have some experience with Visualforce pages (as most of us do, right?), you are probably familiar with the {![expression]} way of accessing attributes. Yes, lightning component is using the same symbol here. {! } simply tells the page, here I am gonna reference something in the attribute (or in the controller, which we will be discussing in the next chapter).

Just like Visualforce components, you can define the attributes of the lightning component or app. We do so by using <aura:attribute>. The name means the attribute name, and type is the type of the attribute, which can be string, number, boolean, SObject or a list. It can also be a custom object.

One thing which might sound alien to you is the v. . So what does v. mean here and why do we need that? Well, lightning component uses this to distinguish whether you are referencing an attribute from the page, or a method in the client side controller. v means view here. But for now, we only need to remember that in order reference a custom attribute in lightning component, we need to have this v. prefix.

Pretty simply, isn’t it?

Next Post

2.1 A simple example using button

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

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