英文:
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:
<div *ngFor="let n of numbers">
{{n}}
<input id="number-{{n}}">
</div>
<button (click)='addNumber()'>Add 5</button>
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):
<div *ngFor="let n of numbers">
{{ n }}
<input #inputRef />
</div>
In ts add this:
@ViewChildren('inputRef')
set inputs(values) {
if (values.length) {
[...values][values.length - 1].nativeElement.focus();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论