Focus on a text box in ember js

advertisements

I am trying to change a text to a text box. If a user clicks the text, it will change to a test box and so they can edit the content. I have done that. I am able to set the focus by below code.

{{input value=animal.name autofocus=true}}

It only works for the first time. If I focus-out, the text box will again change to text content. If I click the text again, I am able to see the text box, but it is not in focus. Below is the code I am trying.

Component file:

import Ember from 'ember';

export default Ember.Component.extend({
  isTextBox: false,
  actions: {
    editTest() {
      this.set('isTextBox', true);
    }
  },
  focusOut() {
    this.set('isTextBox', false);
  },
});

Template file:

{{yield}}
<center><h2>
<div onclick = {{action 'editTest'}}>
{{#if isTextBox}}
{{input value=animal.name autofocus=true}}
{{else}}
{{animal.name}}
{{/if}}
</div>
</h2></center>

I am new to ember and I trying to do the focus without using jQuery.

Here is the twiddle https://ember-twiddle.com/d832c6540ba94901a6c42d5bb3cfa65e?openFiles=templates.components.text-input.hbs%2Ctemplates.components.text-input.hbs.


You can provide id to input helper,

{{input id='cat-text' value=animal.name }}

You can make it focus text field for every rendering,

didRender(){
    this.$('#cat-text').focus();
  }