Interactions
Normalizes the focus event across different browsers and devices.
Input is blurred./** This example uses ng-primitives styles, which are imported from ng-primitives/example-theme/index.css in the global styles file **/
import { Component, signal } from "@angular/core";
import { NgpFocus } from "ng-primitives/interactions";
@Component({
selector: "app-root",
imports: [NgpFocus],
template: `
<input (ngpFocus)="isFocused.set($event)" placeholder="Try focusing me!" />
<p>Input is {{ isFocused() ? "focused" : "blurred" }}.</p>
`,
styles: `
:host {
display: flex;
flex-direction: column;
}
input {
height: 36px;
padding: 0 12px;
border: 1px solid var(--ngp-border);
border-radius: 0.5rem;
box-shadow: var(--ngp-shadow);
outline: none;
}
input[data-focus] {
outline: 2px solid var(--ngp-focus-ring);
outline-offset: 2px;
}
p {
font-size: 0.75rem;
color: var(--ngp-text-secondary);
margin-top: 0.25rem;
}
`,
})
export class AppComponent {
/**
* Whether the input is currently focused.
*/
readonly isFocused = signal<boolean>(false);
}
Import the Focus primitives from ng-primitives/interactions
.
import { NgpFocus } from 'ng-primitives/interactions';
Assemble the focus directives in your template.
<div (ngpFocus)="onFocusChange($event)"></div>
The following directives are available to import from the ng-primitives/interactions
package:
This was inspired by the React Aria useFocus hook.
https://github.com/adobe/react-spectrum/blob/main/packages/%40react-aria/interactions/src/useFocus.ts#L20 Whether listening for focus events is disabled.
Emit when the focus state changes.
[ngpFocus]
ngpFocus
The following data attributes are applied to the ngpFocus
directive:
Attribute | Description |
---|---|
data-focus |
Applied when the element is focused. |
Copyright © 2025 Angular Primitives