47

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
}

How do I set focus to angular2 FormControl or AbstractControl?

7 Answers 7

35

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).

In your component class:

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();
    }
}

If you wanted to focus on the last child...this.rows.last().nativeElement.focus()

And in your template something like:

<div #formRow *ngFor="let row in rows">
    <!-- form row stuff -->
</div>

EDIT:

I actually found a CodePen of someone doing what you're looking for https://codepen.io/souldreamer/pen/QydMNG

4
  • 8
    I think it is @ViewChildren('formRow') rows: QueryList<ElementRef>; Commented Sep 29, 2017 at 8:43
  • 3
    Accessing it as proposed is a direct access to the DOM and so a security risk. Just to attach this info to the accepted answer: You should now use Renderer2 this.renderer.selectRootElement('#input').focus();
    – SWiggels
    Commented Jun 25, 2018 at 7:56
  • 1
    Funny thing selectRootElement is discraced too. So got for the DOM solution.
    – SWiggels
    Commented Jun 25, 2018 at 8:13
  • Yeah, Angular has moved quite a bit since I answered this question a year & a half ago
    – gonzofish
    Commented Jun 27, 2018 at 14:24
16

For Angular 5, combining all of the above answers as follows:

Component relevant code:

 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;
 }

The Template logic Looks like this:

 <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>

In my template I add a record on blur, but you can just as easily set up a button to dynamically add the next input field. The important part is that with this code, the new element gets the focus as desired.

Let me know what you think

1
  • Thanks that worked for me. However I needed to recheck the form for changes. Commented Oct 14, 2020 at 15:43
6

This is the safe method recommend by 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');
  }
}
2
  • 3
    True. On a side note though: Renderer has been deprecated and the now existing Renderer2 does not have invokeElementMethod method on it.
    – user776686
    Commented May 24, 2017 at 19:39
  • 11
    You also could input.nativeElement.focus(); But this is a direct access to the DOM. And so a security risk. Or with Renderer2 this.renderer.selectRootElement('#input').focus(); For completeness.
    – SWiggels
    Commented Jun 25, 2018 at 7:51
2

Per the @Swiggels comment above, his solution for an element of id "input", using his solution after callback:

this.renderer.selectRootElement('#input').focus();

worked perfectly in Angular 12 for an element statically defined in the HTML (which is admittedly different somewhat from the OP's question).

TS:

        @ViewChild('licenseIdCode') licenseIdCodeElement: ElementRef;
        
        // do something and in callback
        ...
        this.notifyService.info("License Updated.", "Done.");
        this.renderer.selectRootElement('#licenseIdCode').focus();

HTML:

               <input class="col-3" id="licenseIdCode"  type="text" formControlName="licenseIdCode"
                   autocomplete="off" size="40" />
0

With angular 13, I did it this way:

import { Component, OnInit, Input } from '@angular/core';
import { FormGroup, Validators, FormControl, FormControlDirective, FormControlName } from '@angular/forms';

// This setting is required
const originFormControlNgOnChanges = FormControlDirective.prototype.ngOnChanges;
FormControlDirective.prototype.ngOnChanges = function ()
{
    this.form.nativeElement = this.valueAccessor._elementRef.nativeElement;
    return originFormControlNgOnChanges.apply(this, arguments);
};

const originFormControlNameNgOnChanges = FormControlName.prototype.ngOnChanges;
FormControlName.prototype.ngOnChanges = function ()
{
    const result = originFormControlNameNgOnChanges.apply(this, arguments);
    this.control.nativeElement = this.valueAccessor._elementRef.nativeElement;
    return result;
};


@Component({
    selector: 'app-prog-fields',
    templateUrl: './prog-fields.component.html',
    styleUrls: ['./prog-fields.component.scss']
})
export class ProgFieldsComponent implements OnInit
{
 ...
 
 generateControls()
    {
        let ctrlsForm = {};
        this.fields.forEach(elem =>
        {
            ctrlsForm[elem.key] = new FormControl(this.getDefaultValue(elem), this.getValidators(elem));
        });
        this.formGroup = new FormGroup(ctrlsForm);
    }
  
  ...
  
  validateAndFocus() 
  {
    if (formGroup.Invalid)
    {
        let stopLoop = false;
        Object.keys(formGroup.controls).map(KEY =>
        {
            if (!stopLoop && formGroup.controls[KEY].invalid)
            {
                (<any>formGroup.get(KEY)).nativeElement.focus();
                stopLoop = true;
            }
        });

        alert("Warn", "Form invalid");
        return;
    }
  }
}

Reference: https://stackblitz.com/edit/focus-using-formcontrolname-as-selector?file=src%2Fapp%2Fapp.component.ts

0

If you are using Angular Material and your <input> is a matInput, you can avoid using .nativeElement and ngAfterViewInit() as follows:

Component Class

import { ChangeDetectorRef, QueryList, ViewChildren } from '@angular/core';
import { MatInput } from '@angular/material/input';
// more imports...

class MyComponent {
    // other variables
    @ViewChildren('theInput') theInputs: QueryList<MatInput>;

    constructor(
      private cdRef: ChangeDetectorRef,
    ) { }

    // ...other code
    addInputToFormArray() {
        // Code for pushing an input to a FormArray

        // Force Angular to update the DOM before proceeding.
        this.cdRef.detectChanges();

        // Use the matInput's focus() method
        this.theInputs.last.focus();
    }
}

Component Template

<ng-container *ngFor="iterateThroughYourFormArrayHere">
    <input #theInput="matInput" type="text" matInput>
</ng-container>
1
  • You can also subscribe to changes QueryList property: this.theInputs.changes.subscribe(res=>res.last.focus()) instead use this.cdRef.detectChanges()
    – Eliseo
    Commented Aug 24, 2022 at 7:14
0
setTimeout(() => {
   this.searchField?.nativeElement.focus();
}, 300)

Full example

@Component({
    selector: 'search-field',
    template: `
        <mat-form-field>
            <input matInput [formControl]="filterControl" placeholder="{{placeholder}}" #searchField>
        </mat-form-field>
    `,
    styleUrls: ["search-field.component.scss"]
    
})
export class SearchFieldComponent implements OnInit, AfterViewInit {

    @Input()
    placeholder = "Поиск"

    @Input()
    autofocus = true

    @Input()
    text: string = ""

    @Output()
    onSearch: EventEmitter<string> = new EventEmitter<string>();

    filterControl = new FormControl("");

    @ViewChild("searchField") searchField?: ElementRef;
    
    ngAfterViewInit(): void {
        if (this.autofocus) {
            setTimeout(() => {
                    this.searchField?.nativeElement.focus();
            }, 300)
        }
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.