Ember autofocus component after insertion into DOM
I want to display an input field and immediately autofocus it by clicking a button. I'm still new to Ember, so I'm not sure if this is the right approach, but I tried to wrap as an ember element
template
{{#if showCalendarForm}}
{{new-calendar focus-out='hideNewCalendar' insert-newline='createCalendar'}}
{{else}}
<button class="btn btn-sm btn-primary" {{action "showNewCalendar"}}>New</button>
{{/if}}
the handles of the new calendar component:
<div class="input-group">
{{input
class = 'form-control'
id = 'newCalendar'
type = 'text'
placeholder = 'New calendar'
value = calendarName
action = 'createCalendar'
}}
</div>
new js calendar component
import Ember from 'ember';
export default Ember.Component.extend({
didInsertElement: function() {
this.$().focus();
}
});
When I click the button, a text box is displayed, but the autofocus and hit function does not work
source to share
As jQuery writes you are trying to set focus to <div class="input-group">
, try this instead:
didInsertElement: function() {
this.$('input').focus();
}
Another way to do this would be by extending Ember.TextField:
export default Ember.TextField.extend({
becomeFocused: function() {
this.$().focus();
}.on('didInsertElement')
});
Then in your new calendar template use this component:
{{focus-input
class = 'form-control'
id = 'newCalendar'
type = 'text'
placeholder = 'New calendar'
value = calendarName
action = 'createCalendar'
}}
This way you can reuse the focus-input component wherever you need it.
As far as pressing to enter to create a calendar, I think you want to listen for the keyPress event, check if it's the enter key, then dispatch the action, not try to use insert-newline='createCalendar'
.
//in FocusInputComponent
keyPress: function(e) {
// Return key.
if (e.keyCode === 13) {
this.sendAction();
}
}
source to share
Try wrapping your focus call in Ember.run and schedule it to run in the post-render queue like this:
didInsertElement: function()
{
Ember.run.scheduleOnce('afterRender', this, function() {
this.$().focus();
});
}
this blog post helped me a lot in understanding the ember lifecycle hooks: http://madhatted.com/2013/6/8/lifecycle-hooks-in-ember-js-views
source to share