1

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"?

Ian Kirkpatrick
  • 1,861
  • 14
  • 33

2 Answers2

1

I've made something similar these days:

component.hbs:

{{#each this.choices as |item|}}
  {{input
    type="text"
    id=item.id
    keyPress=(action this.newElement item)
    value=(mut item.value)
  }}
{{/each}}

component.js

@action
newElement({ id }) {
  let someEmpty = this.choices.some(({ value }) => isBlank(value));

  if (!someEmpty)
    this.choices = [...this.choices, this.generateOption()];

  document.getElementById(id).focus();
}

generateOption(option) {
  this.inc ++;

  if (!option)
    option = this.store.createRecord('option');

  return {
    option,
    id: `${this.elementId}-${this.inc}`,
    value: option.description
  };
}

In my case I have no buttons, and I've created ember data records. With some modifications I bet you can do that!

Bruno Casali
  • 1,339
  • 2
  • 17
  • 32
1

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();
    })
}
Ian Kirkpatrick
  • 1,861
  • 14
  • 33