Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an Angular2 way to focus on an input field?

At the end of a method, I'll be clearing some fields, which is easy enough:

this.modelname.fieldname1 = "";
this.modelname.fieldname2 = "";

After clearing the fields, I'd like the cursor to appear in field1.

Is there an Angular2 way to do this, or do I just use old fashioned Javascript?

like image 780
mojo-jojo Avatar asked Apr 28 '17 22:04

mojo-jojo


People also ask

How do you make an input field focused?

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.

How do you focus an input box in HTML?

Input Text focus() MethodThe focus() method is used to give focus to a text field. Tip: Use the blur() method to remove focus from a text field.

How do you check input is focused or not?

hasFocus() The hasFocus() method of the Document interface returns a boolean value indicating whether the document or any element inside the document has focus. This method can be used to determine whether the active element in a document has focus.


2 Answers

You can use a template reference variable in the first input, that will give you the ability to run .focus() on it.

In your template you can add #fieldName1 to your input tag (i.e. <input type="text" #fieldName1>)

in your controller do:

@ViewChild('fieldName1')
fieldName1: any;

now you can do this.fieldName1.nativeElement.focus() in the controller or fieldName1.focus() in the template.

like image 121
Jose Zamudio Avatar answered Sep 18 '22 18:09

Jose Zamudio


It is not recommended to access dom directly in Angular. Angular provides Renderer (Angular2) and Renderer 2(Angular4) abstractions.

Here is how to do in Angular 2:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input #inp id="myInput" type="text">
      <button (click)="setFocus()">Set Focus</button>
    </div>
  `,
})
export class App {
  @ViewChild('inp') inp:ElementRef;

  constructor(private renderer: Renderer) {
  }

  setFocus() {
    this.renderer.invokeElementMethod(this.inp.nativeElement, 'focus');
  }
}

In Angular4 Renderer is depricated and Renderer2 is added. invokeElementMethod got removed and there is a discussion about it: https://github.com/angular/angular/issues/13818#issuecomment-297815331

Here is Angular 4 way:

 let onElement = this.renderer2.selectRootElement('#myInput');
 onElement.focus();
like image 28
Julia Passynkova Avatar answered Sep 21 '22 18:09

Julia Passynkova