jigAutofocus focuses its host element once, after the first browser render.
It exists because the native autofocus attribute only applies on initial page
load — it does nothing for an element that appears later, which is the common
case in an Angular app (a revealed form, a newly added row, a switched tab).
Put the attribute on any focusable element. The focus happens after the element has actually rendered, so it also works for a control that is still applying its own initialization classes.
Bind the input to turn it off without removing the directive. The focus is
latched: it fires once and never again, so re-rendering or re-showing the
element does not re-steal focus. Setting the input to false releases the latch
— flipping it back to true focuses again.
Focusing is deferred to afterNextRender, which never runs on the server, so
the directive is inert during SSR and hydration. See
SSR & Hydration.
Do not use jigAutofocus on a control inside a closed <jig-dialog>. The
directive latches on the first render — which happens while the dialog is still
closed and its content not focusable — so the focus is spent and nothing is
focused when the dialog opens.
Use the native autofocus attribute on the projected element instead; the
browser applies it when the dialog is shown:
<jig-dialog [(open)]="open">
<jig-input-field [label]="'Name'">
<input jigInput autofocus />
</jig-input-field>
</jig-dialog>For a dialog that is already open on first render, neither mechanism fires. Focus the field yourself once the dialog has been shown:
afterRenderEffect({
read: () => {
if (this.open()) {
this.field()?.nativeElement.focus();
}
},
});
jig