Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to focus on a field?

I updated from Angular 2 to Angular 4 and in the docs it's written to use the Renderer2 instead of Renderer which is deprecated.

Now am looking into the Renderer source, but cannot find a way to invoke the focus() method as I used to.

Old method:

this.renderer.invokeElementMethod(element, 'focus', []);

What is the new aproach?

EDIT

What if the element i am focusing onto is obtained via QuerySelector?

For instance:

let inputField = document.querySelectorAll('.dialog input');
if ( inputField[0] ) {
   inputField[0].focus();
}

Since its obtained via QuerySelector, the focus() method doesn't exist on it.

like image 781
Hassan Avatar asked Mar 24 '17 10:03

Hassan


People also ask

How do you focus an input field?

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 know if a field is in focus?

To detect if the element has the focus in JavaScript, you can use the read-only property activeElement of the document object. const elem = document. activeElement; The activeElement returns the currently focused element in the document.

What is focus field?

A focus field is an interdisciplinary area of study chosen in the junior year and refined in the senior year; it should be associated with the student's senior thesis topic.


1 Answers

If you declare the correct type of your inputField var, you can use any JS query selector.

For instances declaring:
let inputField: HTMLInputElement = document.querySelector('.dialog input');
enables you to call
inputField.focus();
that it will work and no TS error will be thrown.

like image 192
Pedro Ferreira Avatar answered Oct 13 '22 00:10

Pedro Ferreira