How to set focus on element with binding?

后端 未结 9 938
南方客
南方客 2020-12-09 10:23

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

相关标签:
9条回答
  • 2020-12-09 10:44

    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

    0 讨论(0)
  • 2020-12-09 10:46

    The trick is to use both focus and select together:

    this.(element).nativeElement.focus();
    this.(element).nativeElement.select();
    
    0 讨论(0)
  • 2020-12-09 10:48

    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');
        }
    }
    
    0 讨论(0)
提交回复
热议问题