How can I autofocus input element? Similar to this question, but not with AngularDart. Something like this:
autofocus
is a native html feature that should work at least for page initialization. However it fails to work with many angular scenarios, especially with *ngIf
.
You can make a really simple custom directive to get desired behaviour.
import { Directive, OnInit, ElementRef } from '@angular/core';
@Directive({
selector: '[myAutofocus]'
})
export class AutofocusDirective implements OnInit {
constructor(private elementRef: ElementRef) { };
ngOnInit(): void {
this.elementRef.nativeElement.focus();
}
}
The above directive works for my use cases.
How to use
EDIT: There seems to be usecases where it is to early to call focus in the OnInit
lifecycle method. If that is the case, change to OnAfterViewInit
instead.