Loading

Listen to Change Events in Lightning Components

Fecha de publicación: Jul 13, 2023
Descripción
In a Lightning Component, if you have an <aura:attribute> that is being used as the value attribute in a component such as a <lightning:input>, there are two ways you can listen to a change on the input, however, only one is recommended as it lets you modify the input in your controller code.
Solución
If you want to modify the input you should utilize the onchange attribute in the <lightning:input> component. This will allow you to use your controller code to modify the input using component.set(). 

One way you could listen for the change is to make an <aura:handler name="change"> value change component. While this will listen for the change to the <aura:attribute>, in your controller code if you want to modify the input by using component.set(), then you cannot use this method. This is enforced to prevent errors that can occur. One such example is if "foo" was typed into a number field, setting the value back to "" would not actually reset the input to that. 

Incorrect Example:
<aura:attribute name="myValue" type="String">
<aura:handler name="change" value="{!v.myValue}" action="{!c.handleChange}" />
<lightning:input type="text" name="textInput" label="Enter some text" value="{!v.myValue}" />

In your controller code handleChange, component.set("{!v.myValue}", "New text") will not set v.myValue with "New text"

Correct Example:
<aura:attribute name="myValue" type="String">
<lightning:input type="text" name="textInput" label="Enter some text" value="{!v.myValue}" onchange="{!c.handleChange}" />

With this example, in the controller code component.set("{!v.myValue}", "New text") will set myValue with "New text".

For more information, refer to the documentation on the Aura Component Input.
Número del artículo de conocimiento

000380517

 
Cargando
Salesforce Help | Article