4

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?

JB2
  • 1,587
  • 2
  • 24
  • 40

1 Answers1

9

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.

kristjan reinhold
  • 2,038
  • 1
  • 17
  • 34