Newer Version Available

This content describes an older version of this product. View Latest

Component Attributes

Component attributes are like member variables on a class in Apex. They are typed fields that are set on a specific instance of a component, and can be referenced from within the component's markup using an expression syntax. Attributes enable you to make components more dynamic.

Use the <aura:attribute> tag in a component’s markup to add an attribute to the component. Let’s look at a sample component, helloAttributes.cmp:

1swfobject.registerObject("clippy.codeblock-0", "9");<aura:component>
2    <aura:attribute name="whom" type="String" default="world"/>
3    Hello {!v.whom}!
4</aura:component>
5
6

All attributes have a name and a type. Attributes may be marked as required by specifying required="true", and may also specify a default value.

In this case we've got an attribute named whom of type String. If no value is specified, it defaults to "world".

Though not a strict requirement, <aura:attribute> tags are usually the first things listed in a component’s markup, as it provides an easy way to read the component's shape at a glance.

Attribute names must start with a letter or underscore. They can also contain numbers or hyphens after the first character.

You can't use attributes with hyphens in expressions. For example, cmp.get("v.name-withHyphen") is supported, but not <ui:button label="{!v.name-withHyphen}"/>.

Note

If you load helloAttributes.cmp in your browser, it doesn't look any different from the helloWorld.cmp component that we looked at earlier.

Now, append ?whom=you to the URL and reload the page. The value in the query string sets the value of the whom attribute. Supplying attribute values via the query string when requesting a component is one way to set the attributes on that component.

This only works for attributes of type String.

Warning

Expressions

In the markup for helloAttributes.cmp you'll see a line Hello {!v.whom}!. This is what's responsible for the component's dynamic output.

{!<expression>} is the framework's expression syntax. In this case, the expression we are evaluating is v.whom. The name of the attribute we defined is whom, while v. is the value provider for a component's attribute set, which represents the view.

Attribute Validation

We defined the set of valid attributes in helloAttributes.cmp, so the framework automatically validates that only valid attributes are passed to that component.

Try requesting helloAttributes.cmp with the query string ?fakeAttribute=fakeValue. You should receive an error that helloAttributes.cmp doesn’t have a fakeAttribute attribute.