3

Not sure what am i missing here but trying few approaches but still having some issues and it doesn't work so far.

How can I invoke the method focus on a ui input :

cmp

 <lightning:input label="Name" aura:id="itemName" value="{!v.item.Name}"  required="true" />

js

var nameInput = component.find('itemName');
nameInput.focus();

Also tried

component.find('itemName').getElement().focus();
4

This might just be a matter of dom load timing! There are couple of ways you can make it work.

  1. Adding a timer
  2. Using after renderer

Adding a timer

   window.setTimeout(
            $A.getCallback(function () {
                cmp.find("itemName").focus();
            }), 1
        );

Renderer Approach:

afterRender: function (cmp, helper) {
    this.superAfterRender();
   cmp.find("itemName").focus();
}
  • 1
    I like the Renderer approach and using it now. weird that it's not working on simple controller init. Thanks ! – sfdx bomb Dec 20 '18 at 21:05
  • I agree and this.superAfterRender(); will ensure all the default component rendering! This is something similar on Lightning data service and I usually use attribute change handlers in that case! – codeyinthecloud Dec 20 '18 at 21:07
  • +1 but instead of afterRender, render is the easier and preferred approach. – Jayant Das Dec 20 '18 at 22:26
  • @JayantDas Thanks for the suggestion, the reason I went with afterRender is doc states method is called to enable you to interact with the DOM tree after the framework’s rendering service has inserted DOM elements. – codeyinthecloud Dec 20 '18 at 22:31

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.