How to set autofocus in angular or angular 2 not a

2019-04-07 06:11发布

问题:

I see many posts in how to set autofocus on an input filed in angularjs by creating a directive or HTML autofocus, Is there a quick and easy way to set focus in angular (angular 2, angular 4 etc)

回答1:

In your html add #nameit to get its reference in component code.

<input type="text" name="me" #nameit>

Then apply auto fouces into it.

  @ViewChild('nameit') private elementRef: ElementRef;

  public ngAfterViewInit(): void {
    this.elementRef.nativeElement.focus();
  }


回答2:

Aniruddha Das' answer works well in some cases. However, if this is applied to a template-based form with required validation, you may get the following error:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after >it was checked. Previous value: 'false'. Current value: 'true'.

One solution to this is wrapping the focus() call within ngInit() instead of ngAfterViewInit(). So, extending upon Aniduddha's answer:

In your html add the #namedReference to the component:

<input type="text"
    placeholder="Your full name"
    name="name"
    ngModel
    #fullName="ngModel"
    required
    #nameit>

Then use onNgInit() to apply auto focus into it:

@ViewChild('nameit') private elementRef: ElementRef;

ngOnInit() {
    this.elementRef.nativeElement.focus();
}


回答3:

<input id="name" type="text" #myInput />
{{ myInput.focus() }}

Add {{ myInput.focus() }} into your template.



回答4:

you can use the exemple of the most votted answer, but some times you need to put your focus inside of a setTimeout for make a "async" call. In my case i need to put the setTimeout in a selected filter of mat-autocomplete component of angular material.

my code look like this

   setTimeout(() => this.qtdeRef.nativeElement.focus());


回答5:

<input type="text" #textInput placeholder="something" (focus)="someFunction(textInput.value)"/>

or

<input type="text" #textInput placeholder="something" (keyup.enter)="someMethod(textInput.value)"/>