Center element in Aurelia

I want to set focus on a form element. With jQuery it's that simple, just $('selector').focus .

I created a simple <input ref="xxx" id="xxx" type="text"> and in my .ts file I add a property and use it here:

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

Nothing happens. At first I feel that some easy things are becoming difficult, and I am sure that there never was a point.

(The original use case was to set focus on a form element inside Bootstrap camber when crash is shown, for example:

 // set focus to the first element when the add-cell collapse is shown $('#collapsedAddTask').on('shown.bs.collapse', function () { $('#AddTaskTitle').focus() }) 

This works for my main HTML (not a single page application), but not with Aurelia. What is Aurelia?

Update Using the answer from Miroslav Popovich below, and in the comments, I made it work like this (remember that this is a component of the Bootstrap partition):

 <!-- the heading with an A that toggles visibility --> <div class="panel-heading"> <a href="#collapsedAddTask" data-toggle="collapse" id="addTaskHeader" click.delegate="addTaskShown()">Add task</a> </div> <!-- the body, which is initially hidden --> <div class="panel-body"> <div class="collapse" id="collapsedAddCell"> <input type="text" focus.bind="addTaskFocused"> <!-- more controls ... --> </div> </div> 
+5
source share
2 answers

this.xxx.focus() does not work because there is no focus() method for the DOM element. jQuery adds this. The link created by Aurelia points to a simple DOM element. To make it work, you will need to import the jQuery and wrap element:

 import $ from 'jquery'; // ... attached() { $(this.xxx).focus(); } 

In any case, you should avoid using jQuery in normal view models. This is normal to use for custom elements and custom attributes where you need to interact with the DOM or initialize some jQuery plugins.

Aurelia has a custom focus attribute. You can read about this in this Aurelia blog post .

Basically, this allows you to control focus from your view model. In your opinion, you will have the following:

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

And in sight:

 attached() { this.hasFocus = true; } 

Of course, you are likely to use this for more complex scenarios. That is, to focus the input when expanding collapse or when adding a new element to the array associated with repeat.for .

In addition, the focus attribute implements two-way binding. In the above example, it will change the value of the hasFocus property hasFocus .

+8
source

In a situation where the element is not hidden, and you want it to have focus after loading is complete, you can simply add focus.one-time="true" like this:

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

Source: https://habr.com/ru/post/1245066/


All Articles