This is a module for Angular to autofocus an element when it is visible in the DOM.
This package uses an Intersection Observer to detect if an element is visible before focussing it.
This directive will always autofocus an element when it comes into view, making is useful for hidden inputs that come into view after the page is loaded.
The directive also ensures that only one IntersectionObserver instance is created for all components with this directive, preventing extra usage of resources.
ng add ngx-visible-autofocus
OR
npm i ngx-visible-autofocus
ng add ngx-visible-autofocus
Commonly add to app.module.ts
import { NgxVisibleAutofocusModule } from 'ngx-visible-autofocus';
@NgModule({
declarations: [AppComponent],
imports: [..., NgxVisibleAutofocusModule],
bootstrap: [AppComponent],
})
export class AppModule {}
<input type="text" ngxAutofocus />
You can optionally customize the callback.
<input type="text" ngxAutofocus [customCallback]="() => this.focus()" />
You can optionally change the callback setting from only firing once when the element comes into view.
<input type="text" ngxAutofocus [once]="false" />