Focus an element in Aurelia

For the situation where the element isn't hidden and you'd like it to have focus once the view has finished loading, you can simply add focus.one-time="true" like so:

<input
  type="text"
  class="form-control"
  focus.one-time="true"
  value.bind="email"
  placeholder="email address">

this.xxx.focus() is not working because there is no focus() method on DOM element (EDIT: apparently there is now, although Safari does not support it - https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus, thanks @classicalConditioning). jQuery adds that. Reference created by Aurelia points to a plain DOM element. To make it work, you would need to import jQuery and wrap element:

import $ from 'jquery';

// ...

attached() {
    $(this.xxx).focus();
}

Anyway, you should avoid using jQuery in regular view models. It's OK to use it for custom elements and custom attributes, where you need to interact with DOM or initialize some jQuery plugins.

There is a focus custom attribute in Aurelia. You can read more about it in this Aurelia's blog post.

Basically, it enables you to control the focus from your view model. In your view, you would have this:

<input type="text" focus.bind="hasFocus" value.bind="..."/>

And in view model:

attached() {
    this.hasFocus = true;
}

Of course, you'll probably use that for more complex scenarios. I.e. to focus an input when collapse is expanded, or when a new item is added to array bound with repeat.for.

Also, focus attribute implements two-way binding. In the sample above, it will change the value of hasFocus property accordingly.