Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
73
rated 0 times [  77] [ 4]  / answers: 1 / hits: 32516  / 7 Years ago, fri, march 24, 2017, 12:00:00

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.


More From » angular

 Answers
42

The invokeElementMethod is deprecated, and will not find its way back into the new renderer. To set focus to an element, you can simply use this now:



element.nativeElement.focus();


If you are using document.querySelectorAll, you are doing something not the angular way, and you should find another way to do it. If there is no other way to do it, then the same principle applies. The focus() method is plain javascript, so you can use it within angular2/typescript. Be sure to do the querySelectorAll inside the ngAfterViewInit hook of the component though:



ngAfterViewInit() {
let inputField: HTMLElement = <HTMLElement>document.querySelectorAll('.dialog input')[0];
inputField && inputField.focus();
}

[#58405] Wednesday, March 22, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
myakylas

Total Points: 66
Total Questions: 85
Total Answers: 95

Location: Guadeloupe
Member since Sat, Aug 22, 2020
4 Years ago
myakylas questions
Thu, Apr 28, 22, 00:00, 2 Years ago
Thu, Apr 8, 21, 00:00, 3 Years ago
Sat, Sep 19, 20, 00:00, 4 Years ago
;