How to set autofocus in angular or angular 2 not angularjs

元气小坏坏 提交于 2019-11-30 20:46:56

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();
  }

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();
}
Sergey Gurin
<input id="name" type="text" #myInput />
{{ myInput.focus() }}

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

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());
<input type="text" #textInput placeholder="something" (focus)="someFunction(textInput.value)"/>

or

<input type="text" #textInput placeholder="something" (keyup.enter)="someMethod(textInput.value)"/>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!