Ember JS Octane установил фокус на элемент - PullRequest
1 голос
/ 03 февраля 2020

У меня есть компонент, который содержит несколько текстовых областей и кнопку для добавления другой текстовой области. Когда пользователь нажимает кнопку, добавляется новая текстовая область. Я хочу, чтобы фокус переместился в эту новую текстовую область.

Я видел этот ответ , но он для более старой версии, и мы не используем jQuery с Ember.

Что у меня есть:

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 }}" />

Краткое содержание вопроса

Как установить фокус на новую область текста после того, как пользователь нажмет «Добавить почему»?

Ответы [ 2 ]

1 голос
/ 13 марта 2020

Обнаружено, что я могу использовать Ember.run.schedule для запуска кода после повторного рендеринга компонента.

@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();
    })
}
1 голос
/ 10 февраля 2020

Я сделал нечто похожее в эти дни:

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

В моем случае у меня нет кнопок, и я создал записи данных ember. С некоторыми изменениями, держу пари, вы можете сделать это!

...