How to set focus on element with binding?

后端 未结 9 961
南方客
南方客 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: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 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');
        }
    }
    

提交回复
热议问题