我似乎无法在动态添加的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).
原文链接:https://www.f2er.com/angularjs/140331.html在您的组件类中:
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