How to set autofocus in angular or angular 2 not angularjs

北慕城南 提交于 2019-11-30 04:23:27

问题


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)"/>


来源:https://stackoverflow.com/questions/42861734/how-to-set-autofocus-in-angular-or-angular-2-not-angularjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!