How to focus certain input elements in Ember 2

I am learning Ember 2 and trying to write a simple built-in editor. My problem is the auto focus of the input element. The component template is as follows:

{{#if isEditing}}
    {{input type="text" placeholder="Line item" autofocus="autofocus" value=value class="form-control" focus-out="save"}}
{{/if}}
{{#unless isEditing}}
    <a href="#" {{action "toggleEditor"}}>{{value}}</a>
{{/unless}}

With controller:

import Ember from 'ember';

export default Ember.Component.extend({
    actions: {
        toggleEditor: function () {
            this.set('isEditing', !this.get('isEditing'));
        },
        save: function () {
            var object = this.get('object');
            var property = this.get('property');
            object.set(property, this.get('value'));
            var promise = object.save();
            promise.finally(() => {
                this.send('toggleEditor');
            });
        }
    }
});

Use autofocus="autofocus"works when setting the parameter isEditingto true. However, when the anchor element is visible and the user clicks on the link, focus will not be transferred to the newly visible input element. So my question is: what is the best way to focus the input element? Inside toggleEditor, how do I access an input element by ID and how to focus it using Ember?

+4
source share
1

.

this.toggleProperty('propertyName');

if/else.

{{#if isEditing}}
    {{input type="text" placeholder="Line item" class="my-input"}}
{{else}}
    <a href="#" {{action "toggleEditor"}}>{{value}}</a>
{{/if}}

, , .

toggleIsEditing: function() {
        this.toggleProperty('isEditing');

        if(this.get('isEditing')) {
            Ember.run.scheduleOnce('afterRender', this, function() {
                $('.my-input').focus();
            });  
        }
},

tho.

+9

All Articles