动态添加一个新元素,并在渲染后对其进行焦点设置。

huangapple go评论109阅读模式
英文:

Dynamically add a new element and focus it after rendering

问题

我正在尝试弄清楚如何专注于动态添加并从 ngFor 渲染的元素。

在模板中,我有一个简单的迭代器,它遍历一个数字数组并为每个数字生成一个输入框:

  1. <div *ngFor="let n of numbers">
  2. {{n}}
  3. <input id="number-{{n}}">
  4. </div>
  5. <button (click)='addNumber()'>Add 5</button>

我在列表末尾有一个按钮,用于添加新的数字。

在 .ts 文件中,我有以下内容:

  1. // numbers 是从父组件传入的输入,简单地是 [1,2,3,4]
  2. addNumber() {
  3. this.numbers.push(5);
  4. this.focusLast(5);
  5. }
  6. focusLast(number) {
  7. const htmlElement = document.getElementById(`number-${number}`);
  8. // 控制台日志显示为 null
  9. console.log(htmlElement);
  10. // 需要选择并专注于它
  11. htmlElement?.focus();
  12. }

我无法选择最后添加的元素,因为它尚未呈现,因此无法对其进行专注。如何最简单地实现这一目标呢?

这是我的 stackblitz 示例

英文:

I'm trying to work out how to focus on an element that's being added dynamically and rendered from a ngFor.

In the template, I have a simple iterator that goes through an array of numbers and generates an input for each number:

  1. &lt;div *ngFor=&quot;let n of numbers&quot;&gt;
  2. {{n}}
  3. &lt;input id=&quot;number-{{n}}&quot;&gt;
  4. &lt;/div&gt;
  5. &lt;button (click)=&#39;addNumber()&#39;&gt;Add 5&lt;/button&gt;

I have a button at the end of the list that adds a new number.

In the .ts file I have the following:

  1. // numbers is an input from parent component and is simply [1,2,3,4]
  2. addNumber() {
  3. this.numbers.push(5);
  4. this.focusLast(5);
  5. }
  6. focusLast(number) {
  7. const htmlElement = document.getElementById(`number-${number}`);
  8. // console log shows null
  9. console.log(htmlElement);
  10. // need to select and focus on it
  11. htmlElement?.focus();
  12. }

I can't select the last element I added as it hasn't been rendered yet and therefore I can't focus on it. What's the easiest way to achieve this?

Here is my stackblitz example

答案1

得分: 2

UPDATED:

有几种方法可以实现这个目标。一种简单的方法是实现这个目标并避免直接访问 DOM。

在模板中添加模板引用(inputRef):

  1. <div *ngFor="let n of numbers">
  2. {{ n }}
  3. <input #inputRef />
  4. </div>

在 TypeScript 中添加以下内容:

  1. @ViewChildren('inputRef')
  2. set inputs(values) {
  3. if (values.length) {
  4. [...values][values.length - 1].nativeElement.focus();
  5. }
  6. }
英文:

UPDATED:

There are several ways to achieve this. One easy way to achieve this and to avoid direct DOM access.

In template add template reference (inputRef):

  1. &lt;div *ngFor=&quot;let n of numbers&quot;&gt;
  2. {{ n }}
  3. &lt;input #inputRef /&gt;
  4. &lt;/div&gt;

In ts add this:

  1. @ViewChildren(&#39;inputRef&#39;)
  2. set inputs(values) {
  3. if (values.length) {
  4. [...values][values.length - 1].nativeElement.focus();
  5. }
  6. }

huangapple
  • 本文由 发表于 2023年5月24日 17:18:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76321927.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定