Set focus to textarea in ember js

I am trying to change the text in a textbox. If the user clicks on the text, he switches to the test field and therefore can edit the content. I did it. I can set focus to below code.

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

      

It only works the first time. If I focus, the textbox changes to text content again. If I click the text again, I can see the textbox, but it is out of focus. Below is the code I am trying to do.

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 am trying to do focus without using jQuery.

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

+3


source to share


3 answers


You can provide id for helper input,

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

      



You can make this focal text box for every render,

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

      

+1


source


You can do it in plain old Javascript like this:

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();
}

      

It assumes you have an input like this:



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

      

Ember 2.13+ no longer relies on jQuery (although some of the add-ons you use might be), so you have the option to eliminate the 35kb (min + gzip) that jQuery will add to your application's payload.

+4


source


To expand on kumkanillam's answer, you can simply set focus at the end of the render lifecycle if it renders the textbox. Since you only have one text input in your component, you can simply find it using a selector. No need to worry about using jQuery here that it's there, so this is the Ember way.

didRender(){
  if(this.get('isTextBox')){
    this.$('input[type=text]:first').focus();
  }
}

      

+2


source







All Articles