In Angular2 how can I set binding on element focus. I don\'t want to set it with elementRef. I think in AngularJS there is ngFocus directive In Angular2 there is no such dir
The best way of setting focus on an element with angular2 is by using the Renderer
and invoke an method on the element. There is no way of doing this without elementRef
.
This results in something like this:
this.renderer.invokeElementMethod(this.input.nativeElement, 'focus', []);
Where renderer
gets injected in the constructor using protected renderer : Renderer
The trick is to use both focus and select together:
this.(element).nativeElement.focus();
this.(element).nativeElement.select();
I tried both variants but none is suitable for simple use. 1st (by @AngJobs) needs additional work in component where you use directive (to set focus=true), 2nd (by @ShellZero) not working at all because focus called before the view is actually ready. So I moved focus call to ngAfterViewInit
. Now you can just add <input focus...
and forget it. Element will get focus after view init automatically.
import { Directive, ElementRef, Renderer, AfterViewInit } from '@angular/core';
@Directive({
selector: '[focus]'
})
export class DmFocusDirective implements AfterViewInit {
constructor(private _el: ElementRef, private renderer: Renderer) {
}
ngAfterViewInit() {
this.renderer.invokeElementMethod(this._el.nativeElement, 'focus');
}
}