javascriptember.jsfocusautofocusember-octane

EmberJS Octane set focus on element


I have component that contains a number of text areas and a button to add another text area. When the user clicks the button, a new text area is added. I want the focus to move to this new text area.

I saw this answer but it's for an older version and we are not using jQuery with Ember.

What I have so far:

five-whys.ts

type LocalWhy = {
  content: string;
};

export default class FiveWhys extends Component<FiveWhysArgs> {
  @tracked
  whys: LocalWhy[] = ...

  @action
  addWhy() {
    this.whys.pushObject({ content: "" });
  }
}

five-whys.hbs

{{#each this.whys as |why i|}}
  <TextQuestion @value={{why.content}} />
{{/each}}

<button {{on "click" (action this.addWhy)}}>Add Why</button>

text-question.hbs

...
<textarea value="{{ @value }}" />

Summary of question

How do I set the focus to the new textarea after the user clicks "Add Why"?


Solution

  • Found out I can use Ember.run.schedule to run code after the component re-renders.

    @action
    addWhy() {
        ... // Adding why field
        Ember.run.schedule('afterRender', () => {
          // When this function has called, the component has already been re-rendered
          let fiveWhyInput = document.querySelector(`#five-why-${index}`) as HTMLTextAreaElement
          if (fiveWhyInput)
            fiveWhyInput.focus();
        })
    }