Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to focus specific input elements in Ember 2

I am learning Ember 2, and trying to write a simple inline editor. My problem is auto-focusing the input element. The component's 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 the controller being:

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');
            });
        }
    }
});

Using autofocus="autofocus" works when setting the isEditing parameter to true. However, when the anchor element is visible, and the user clicks on the link, the focus won't transfer to the newly visible input element. My question therefore is: what's the best way of focusing the input element? Inside toggleEditor, how do I access the input element by ID and how can I focus it using Ember?

like image 488
JB2 Avatar asked Jan 06 '23 07:01

JB2


1 Answers

There's a better way to toggle properties.

this.toggleProperty('propertyName');

Also consider using if/else.

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

The way i got it working was to write an action like this.

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

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

Weird stuff tho.

like image 72
kris Avatar answered Feb 12 '23 21:02

kris