窗体 – 如何以编程方式将焦点设置为Angular2中动态创建的FormCo
发布时间:2020-12-17 09:57:06 所属栏目:安全 来源:网络整理
导读:我似乎无法在动态添加的FormGroup中将焦点设置在输入字段上: addNewRow(){ (FormArraythis.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 Form
|
我似乎无法在动态添加的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?
您不能设置为FormControl或AbstractControl,因为它们不是DOM元素.您需要做的是以某种方式对它们进行元素引用,并在其上调用.focus().您可以通过ViewChildren实现此目的(目前API文档不存在,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() 在你的模板中,例如: <div #formRow *ngFor="let row in rows">
<!-- form row stuff -->
</div>
编辑: 我实际上发现了一个CodePen,有人在做你正在寻找的东西https://codepen.io/souldreamer/pen/QydMNG (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
