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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With