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

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

Dynamically add a new element and focus it after rendering

问题

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

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

<div *ngFor="let n of numbers">
  {{n}}
  <input id="number-{{n}}">
</div>

<button (click)='addNumber()'>Add 5</button>

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

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

// numbers 是从父组件传入的输入,简单地是 [1,2,3,4]

addNumber() {
  this.numbers.push(5);
  this.focusLast(5);
}
    
focusLast(number) {
  const htmlElement = document.getElementById(`number-${number}`);
  // 控制台日志显示为 null
  console.log(htmlElement);
  // 需要选择并专注于它
  htmlElement?.focus();
}

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

这是我的 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:

&lt;div *ngFor=&quot;let n of numbers&quot;&gt;
  {{n}}
  &lt;input id=&quot;number-{{n}}&quot;&gt;
&lt;/div&gt;

&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:


// numbers is an input from parent component and is simply [1,2,3,4]

addNumber() {
  this.numbers.push(5);
  this.focusLast(5);
}
    
focusLast(number) {
  const htmlElement = document.getElementById(`number-${number}`);
  // console log shows null
  console.log(htmlElement);
  // need to select and focus on it
  htmlElement?.focus();
}

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):

<div *ngFor="let n of numbers">
  {{ n }}
  <input #inputRef />
</div>

在 TypeScript 中添加以下内容:

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

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):

&lt;div *ngFor=&quot;let n of numbers&quot;&gt;
  {{ n }}
  &lt;input #inputRef /&gt;
&lt;/div&gt;

In ts add this:

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

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:

确定