Angular2+ autofocus input element

后端 未结 10 2053
走了就别回头了
走了就别回头了 2020-12-07 18:24

How can I autofocus input element? Similar to this question, but not with AngularDart. Something like this:



        
10条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 19:08

    If you don't need true/false functionality, but want autofocus set always, there's a shorter implementation to Makla's solution:

    autofocus.directive.ts:

    import { Directive, ElementRef, Input, OnInit } from '@angular/core';
    
    @Directive({
        selector: '[autofocus]'
    })
    
    export class AutofocusDirective implements AfterViewInit {
    
        constructor(private el: ElementRef) {
        }
    
        ngAfterViewInit() {
            // Otherwise Angular throws error: Expression has changed after it was checked.
            window.setTimeout(() => {
                this.el.nativeElement.focus();
            });
        }
    }
    

    use case:

     //will focus
    

    Using AfterViewInit instead of OnInit makes the cursor placed after the content inside input field, should it get populated.

    Remember to declare and export autofocus directive in your module!

提交回复
热议问题