Angular2+ autofocus input element

后端 未结 10 2008
走了就别回头了
走了就别回头了 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:15

    Starting from IE11, as all other modern browsers, the native HTML autofocus Attribute for inputs should work fine too without tying on Angular:

    <input autofocus>
     
    <input type="text" [(ngModel)]="title" autofocus>
    
    0 讨论(0)
  • 2020-12-07 19:16

    The following directive works for me using Angular 4.0.1

    import {Directive, ElementRef, AfterViewInit} from '@angular/core';
    
    @Directive({
      selector: '[myAutofocus]'
    })
    export class MyAutofocusDirective implements AfterViewInit {
      constructor(private el: ElementRef)
      {
      }
      ngAfterViewInit()
      {
        this.el.nativeElement.focus();
      }
    }
    

    use it like this:

    <md-input-container>
        <input mdInput placeholder="Item Id" formControlName="itemId" name="itemId" myAutofocus>
    </md-input-container>
    

    The option of using OnInit lifecycle event did not work for me. I also tried using the Renderer in the other answer which didn't work for me.

    0 讨论(0)
  • 2020-12-07 19:19

    I know this is an old post but for others looking for a newer answer: I was using an angular material dialog and it was auto-selecting the close button not the input.

    Using cdk-focus-start (part of the CDK) fixes this ... with no additional code.

    0 讨论(0)
  • 2020-12-07 19:21

    Try this simple but effective function.:

    function addFocusInput() {
      document.getElementById('text-focus').focus();
    }
    
    addFocusInput();
    <input id="text-focus" type="text" placeholder=""/>

    0 讨论(0)
提交回复
热议问题