How to set focus on element with binding?

后端 未结 9 979
南方客
南方客 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:40

    A simple 'focus' Directive

    import {Directive, Input, ElementRef} from 'angular2/core';
    @Directive({
        selector: '[focus]'
    })
    class FocusDirective {
        @Input()
        focus:boolean;
        constructor(@Inject(ElementRef) private element: ElementRef) {}
        protected ngOnChanges() {
            this.element.nativeElement.focus();
        }
    }
    
    // Usage
    @Component({
        selector : 'app',
        template : `
            
            
        `,
        directives: [FocusDirective]
    })
    export class App {
        private inputFocused = false;
        moveFocus() {
            this.inputFocused = true;
            // we need this because nothing will 
            // happens on next method call, 
            // ngOnChanges in directive is only called if value is changed,
            // so we have to reset this value in async way,
            // this is ugly but works
            setTimeout(() => {this.inputFocused = false});
        }
    }
    

提交回复
热议问题