Interactions
Determine whether focus should be visible based on user interaction. This is useful for accessibility and user experience, as it allows you to provide visual feedback when an element is focused using keyboard navigation, while not showing the focus outline when the user is using a mouse or touch device.
import { Component } from "@angular/core";
import { NgpFocusVisible } from "ng-primitives/interactions";
@Component({
selector: "app-focus-visible",
imports: [NgpFocusVisible],
template: ` <button ngpFocusVisible>Try focusing me!</button> `,
styles: `
button {
padding-left: 1rem;
padding-right: 1rem;
border-radius: 0.5rem;
color: var(--ngp-text-primary);
outline: none;
height: 2.5rem;
font-weight: 500;
background-color: var(--ngp-background);
border: 1px solid var(--ngp-border);
transition: background-color 300ms cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: var(--ngp-shadow);
}
button[data-focus-visible] {
outline: 2px solid var(--ngp-focus-ring);
outline-offset: 2px;
}
`,
})
export default class FocusVisibleExample {}
Import the Focus Visible primitives from ng-primitives/interactions
.
import { NgpFocusVisible } from 'ng-primitives/interactions';
Assemble the focus-visible directives in your template.
<div (ngpFocusVisible)="onFocusVisible($event)"></div>
The following directives are available to import from the ng-primitives/interactions
package:
Apply the `ngpFocusVisible` directive to an element that should be visually focused. This is similar to `ngpFocus`
but it will only apply the focus visible styles when the element is focused via keyboard navigation. Whether focus events are listened to.
Emit when the element is visually focused.
[ngpFocusVisible]
ngpFocusVisible
The following data attributes are applied to the ngpFocusVisible
directive:
Attribute | Description |
---|---|
data-focus-visible |
Applied when the element is focused via keyboard navigation. |
Copyright © 2025 Angular Primitives