Set focus on a text box in ember js

Sri*_*m G 4 ember.js

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}}
Run Code Online (Sandbox Code Playgroud)

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);
  },
});
Run Code Online (Sandbox Code Playgroud)

Template file:

{{yield}}
<center><h2>
<div onclick = {{action 'editTest'}}>
{{#if isTextBox}}
{{input value=animal.name autofocus=true}}
{{else}}
{{animal.name}}
{{/if}}
</div>
</h2></center>
Run Code Online (Sandbox Code Playgroud)

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

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

cas*_*red 5

您可以在普通旧 Javascript 中执行此操作,如下所示:

didRender(){
    // This works but is not very ember-ish
    // document.getElementById('cat-text').focus();

    // For a component, you can do this
    this.get('element').querySelector("#cat-text").focus();
}
Run Code Online (Sandbox Code Playgroud)

这假设您有这样的输入:

{{input id='cat-text' value=animal.name }}
Run Code Online (Sandbox Code Playgroud)

Ember 2.13+ 不再依赖于 jQuery(尽管您使用的一些附加组件可能是),因此您有可能消除 jQuery 将添加到您的应用程序负载的 35kb(最小 + gzip)。