How can I autofocus input element? Similar to this question, but not with AngularDart. Something like this:
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>
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.
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.
Try this simple but effective function.:
function addFocusInput() {
document.getElementById('text-focus').focus();
}
addFocusInput();
<input id="text-focus" type="text" placeholder=""/>