7

There are 2 ways to get values from UI in JS controller.

  1. component.get("v.name");
  2. component.find("name");

My question is when both can serve the same purpose, which one to use and when?

9

That's not entirely the case because when using component.find() it returns instance(s) of type Aura.Component only, you need to use component.get() method to access the data from respective component(UI).

As far as data access is concerned there are two ways we can do it:

1) Using component's accessor method:

  component.get("v.attributeName") // returns the value directly

2) Get the values using the component instances:

2.1) Find the component instance:

 // returns the instance(s) of type Aura.Component
 var cmpInstance = component.find("auraid") 

2.2) Get the value using access method:

// works if only if one instance is component is present
cmpInstance.get("v.attributeName") (if cmpInstance returns array, then iterate)

// if multiple instances exist then, iterate and access the value

for(var i = 0; cmpInstance.length; i++) {
    cmpInstance[i].get("v.attributeName");
}

In general we can use component.find() to access public or global(for managed package) attributes and methods(aura:method) of components

4

The find() function has one parameter, which is the local ID of a component within the markup.

find() returns different types depending on the result.

  1. If the local ID is unique, find() returns the component.

  2. If there are multiple components with the same local ID, find() returns an array of the components.

  3. If there is no matching local ID, find() returns undefined.

Component.get() can be used to retrieve attribute value. From documentaion

component.get(String key) and component.set(String key, Object value) retrieves and assigns values associated with the specified key on the component. Keys are passed in as an expression, which represents attribute values.

We can conclude that, component.find() works in a more broader way whereas component.get() is associated with attributes. find() method can be used to work on tags having same id's simultaneously.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.