如何以编程方式将焦点设置为Angular2中动态创建的FormControl

时间:2016-12-16 18:07:46

标签: forms angular

我似乎无法将注意力集中在动态添加的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?

3 个答案:

答案 0 :(得分:14)

您无法设置为FormControlAbstractControl,因为它们不是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>

编辑:

我实际上找到了某人正在寻找你正在寻找的https://codepen.io/souldreamer/pen/QydMNG

的CodePen

答案 1 :(得分:6)

对于Angular 5,结合以上所有答案如下:

组件相关代码:

 import { AfterViewInit, QueryList, ViewChildren, OnDestroy } from '@angular/core';
 import { Subscription } from 'rxjs/Subscription';

 // .. other imports

 export class MyComp implements AfterViewInit, OnDestroy {
   @ViewChildren('input') rows: QueryList<any>;
   private sub1:Subscription = new Subscription();
   //other variables ..

 // changes to rows only happen after this lifecycle event so you need
 // to subscribe to the changes made in rows.  
 // This subscription is to avoid memory leaks
 ngAfterViewInit() {
   this.sub1 = this.rows.changes.subscribe(resp => {
     if (this.rows.length > 1){
       this.rows.last.nativeElement.focus();
     }
   });
  }

  //memory leak avoidance
  ngOnDestroy(){
    this.sub1.unsubscribe();
  }


   //add a new input to the page
   addInput() {
     const formArray = this.form.get('inputs') as FormArray;

     formArray.push(
        new FormGroup(
        {input: new FormControl(null, [Validators.required])}
     ));
    return true;
   }

 // need for dynamic adds of elements to re 
 //focus may not be needed by others
 trackByFn(index:any, item:any){
    return index;
 }

模板逻辑看起来像这样:

 <div formArrayName="inputs" class="col-md-6 col-12" 
     *ngFor="let inputCtrl of form.get('phones').controls; 
             let i=index; trackBy:trackByFn">
     <div [formGroupName]="i">
        <input #input type="text" class="phone" 
             (blur)="addRecord()"
             formControlName="input" />
     </div>
 </div>

在我的模板中,我添加了模糊记录,但您可以轻松设置按钮以动态添加下一个输入字段。重要的是,使用此代码,新元素可以根据需要获得焦点。

让我知道你的想法

答案 2 :(得分:1)

这是angular

推荐的安全方法
@Component({
  selector: 'my-comp',
  template: `
    <input #myInput type="text" />
    <div> Some other content </div>
  `
})
export class MyComp implements AfterViewInit {
  @ViewChild('myInput') input: ElementRef;

  constructor(private renderer: Renderer) {}

  ngAfterViewInit() {
    this.renderer.invokeElementMethod(this.input.nativeElement,    
    'focus');
  }
}