Skip to main content
cngx-src documentation

CngxAutofocus

DirectivePrimaryv0.1.0WCAG AA

projects/common/a11y/focus/autofocus.directive.ts

Import#

import { CngxAutofocus } from '@cngx/common/a11y'

Description#

Reactive autofocus for dynamically inserted elements.

The native autofocus HTML attribute only works on initial page load. This directive handles dynamic content: dialogs, panels, stepper steps, and any element that appears after the initial render.

Focuses the host element after the next render frame using afterNextRender. When when changes to true, focus is re-applied.

Focus on insertion

@if (showSearch()) {
  <input cngxAutofocus placeholder="Search…" />
}

Conditional focus

<input [cngxAutofocus]="isActive()" />

With delay for transitions

<input cngxAutofocus [autofocusDelay]="200" />

https://cngxjs.github.io/cngx/examples/#/common/a11y/autofocus/conditional-focus https://cngxjs.github.io/cngx/examples/#/common/a11y/autofocus/focus-on-insert

Metadata#

Index#

Inputs#

delay#number
input()

Delay in ms before focusing - useful when the element appears during a transition.

default 0, { alias: 'autofocusDelay' }
options#FocusOptions
input()

FocusOptions passed to element.focus().

default {}, { alias: 'autofocusOptions' }
input()

Whether to focus the element. Defaults to true (always focus on render).

default true, { alias: 'cngxAutofocus' }