如何在Angular2中以编程方式将焦点设置为动态创建的FormControl [英] How do I programmatically set focus to dynamically created FormControl in Angular2
问题描述
我似乎无法将焦点放在动态添加的FormGroup中的输入字段上:
I don't seem to be able to set focus on a input field in dynamically added FormGroup:
addNewRow(){
(<FormArray>this.modalForm.get('group1')).push(this.makeNewRow());
// here I would like to set a focus to the first input field
// say, it is named 'textField'
// but <FormControl> nor [<AbstractControl>][1] dont seem to provide
// either a method to set focus or to access the native element
// to act upon
}
如何将焦点设置为angular2 FormControl或AbstractControl?
How do I set focus to angular2 FormControl or AbstractControl?
推荐答案
我在2016年12月发表了这篇文章,自那时以来Angular取得了长足的进步,因此我将确保从其他来源了解这仍然是一种合法的方式做事
您不能将其设置为FormControl
或AbstractControl
,因为它们不是DOM元素.您需要做的是以某种方式对它们进行元素引用,然后在其上调用.focus()
.您可以通过ViewChildren
(目前不存在API文档,2016-12-16)来实现此目标.
I made this post back in December 2016, Angular has progressed significantly since then, so I'd make sure from other sources that this is still a legitimate way of doing things
You cannot set to a FormControl
or AbstractControl
, since they aren't DOM elements. What you'd need to do is have an element reference to them, somehow, and call .focus()
on that. You can achieve this through ViewChildren
(of which the API docs are non-existent currently, 2016-12-16).
在您的组件类中:
import { ElementRef, ViewChildren } from '@angular/core';
// ...imports and such
class MyComponent {
// other variables
@ViewChildren('formRow') rows: ElementRef;
// ...other code
addNewRow() {
// other stuff for adding a row
this.rows.first().nativeElement.focus();
}
}
如果您想关注最后一个孩子... this.rows.last().nativeElement.focus()
If you wanted to focus on the last child...this.rows.last().nativeElement.focus()
在您的模板中,诸如:
<div #formRow *ngFor="let row in rows">
<!-- form row stuff -->
</div>
我实际上发现一个CodePen有人在做您要寻找的东西 https://codepen.io/souldreamer/pen/QydMNG
I actually found a CodePen of someone doing what you're looking for https://codepen.io/souldreamer/pen/QydMNG
这篇关于如何在Angular2中以编程方式将焦点设置为动态创建的FormControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!