This is a general question aimed at finding best approach to do some task. Now I interested in how should I get values from inputs in lightning components. Let's say I have a component:
Example.cmp
<aura:component controller="ExampleController">
<aura:attribute name="exampleDatetime" type="DateTime" access="private" />
<aura:attribute name="isVisible" type="Boolean" default="false" access="private" />
<aura:if isTrue="{! v.isVisible }">
<lightning:input
type="datetime"
aura:id="exampleDatetimeInput"
name="exampleDatetimeInput"
label="Example Datetime Input"
value="{! v.exampleDatetime }"
/>
</aura:if>
<lightning:button label="Example" onclick="{! c.onClick }" />
<lightning:button label="Show Input" onclick="{! c.onClickShowInput }" />
</aura:component>
ExampleController.js
({
onClick: function(component, event, helper) {
const action = component.get("c.exmapleServerAction");
const data = component.get("v.exampleDatetime");
// OR
// const data = component.find("exampleDatetimeInput").get("v.value");
action.setParam("exmapleServerDataParam", data);
action.setCallback(this, function(response) {
// skipped for brevity
});
$A.enqueueAction(action);
},
onClickShowInput: function(component, event, helper) {
// Toggle visibility
const isVisible = component.get("v.isVisible");
component.set("v.isVisible", !isVisible);
}
})
Should I event create this exampleDatetime
attribute at all if the only thing I need is actual value provided by user in the input field? This attribute seems redundant so I feel it can be removed, but I am not sure if this is a good practice to access component's value directly though?
component.get("v.exampleDatetime");
andcomponent.find("exampleDatetimeInput").get("v.value");
?