How do you show focus rings on custom filter chips only for keyboard users with the Angular CDK's `FocusMonitor`, and what breaks after programmatic focus?
answer
- how, not just whether
- four origins and null
- classes on the element
- plain focus() reports program
- focusVia states the origin
basics
~20 sFocusMonitor.monitor(element) reports how focus arrived, as keyboard, mouse, touch or program, and adds classes such as cdk-keyboard-focused, so a ring styled on that class shows only for keyboard focus. A plain focus() call reports program; use focusVia(element, origin).
solid answer
~40 s`FocusMonitor` from `@angular/cdk/a11y` watches an element and emits a `FocusOrigin`: `'keyboard'`, `'mouse'`, `'touch'`, `'program'`, or `null` on blur. While focused it adds `cdk-focused` plus one of `cdk-keyboard-focused`, `cdk-mouse-focused`, `cdk-touch-focused` or `cdk-program-focused`, so styling the ring on `.cdk-keyboard-focused` limits it to keyboard users. `cdkMonitorElementFocus` does the same declaratively, with a `cdkFocusChange` output. The trap is code that moves focus itself, such as returning focus to a chip after a drawer's close animation: with no key, mouse or touch event in the current or previous tick the origin is `'program'`, so a keyboard user loses the ring. Record the origin that opened the drawer and restore with `focusVia(chip, origin)`. Always call `stopMonitoring` on destroy.
code
ts · 24 linesimport {Directive, ElementRef, OnDestroy, inject} from '@angular/core';
import {FocusMonitor, FocusOrigin} from '@angular/cdk/a11y';
@Directive({selector: '[appFilterChip]', host: {class: 'filter-chip'}})
export class FilterChip implements OnDestroy {
private el = inject<ElementRef<HTMLElement>>(ElementRef);
private focusMonitor = inject(FocusMonitor);
lastOrigin: FocusOrigin = null;
constructor() {
this.focusMonitor.monitor(this.el).subscribe(origin => {
if (origin) this.lastOrigin = origin;
});
}
// Restore focus with the origin that opened the drawer.
restoreFocus(origin: FocusOrigin): void {
this.focusMonitor.focusVia(this.el, origin);
}
ngOnDestroy(): void {
this.focusMonitor.stopMonitoring(this.el);
}
}go deeper
Recall that FocusMonitor tells you whether focus came from keyboard, mouse, touch or code, and adds matching cdk classes.
Explain monitor, the origin values, the class names, the two directives and why stopMonitoring is required.
Diagnose the missing ring after programmatic focus and fix it by carrying the origin through focusVia, including key manager origins and detection modes.
Choose between FocusMonitor classes and the browser's :focus-visible across a codebase, and make focus restoration consistent in every overlay and drawer.
## Why `focus` and `blur` events are not enough A `focus` event tells you that an element received focus, not **how**. Designers usually want a strong focus ring for keyboard users, who need it to see where they are, and no ring after a mouse click, where it looks like a glitch. The Angular CDK's **`FocusMonitor`** service, in `@angular/cdk/a11y`, answers the 'how' by watching the interaction events that precede focus. ## The API - `monitor(element, checkChildren = false)` starts watching an element or `ElementRef` and returns an `Observable<FocusOrigin>`. - `FocusOrigin` is `'touch' | 'mouse' | 'keyboard' | 'program' | null`; `null` means the element blurred. - With `checkChildren` set to `true`, focus on any descendant counts as focus on the element. - `stopMonitoring(element)` removes the classes, completes the observable and detaches listeners; call it when the element's owner is destroyed. - `focusVia(element, origin)` focuses an element and records the origin you name; for an element already focused, it just updates the classes. While an element is focused the service toggles CSS classes on it: | Origin | Classes added | |---|---| | keyboard | `cdk-focused`, `cdk-keyboard-focused` | | mouse | `cdk-focused`, `cdk-mouse-focused` | | touch | `cdk-focused`, `cdk-touch-focused` | | program | `cdk-focused`, `cdk-program-focused` | | blurred | all removed | Two directives wrap the service: **`cdkMonitorElementFocus`** (`checkChildren` false) and **`cdkMonitorSubtreeFocus`** (`checkChildren` true). Both emit the origin from a `cdkFocusChange` output and stop monitoring on destroy. ## Keyboard-only rings on filter chips 1. Monitor each chip, through the directive or by calling `monitor` in the chip's own directive. 2. Style the ring on `.cdk-keyboard-focused`, and remove the browser's default outline only when the element is `.cdk-focused` without that class. 3. Call `stopMonitoring` when the chip is destroyed. Angular Material's own components rely on these classes; its buttons, for instance, show their focus state for both `cdk-keyboard-focused` and `cdk-program-focused`. ## What breaks after programmatic focus The service decides the origin from the most recent `keydown`, `mousedown` or `touchstart`, and in its default mode only from one in the current or previous tick. When code moves focus outside that window, for example after a close animation, a timer or a server response, the origin is `'program'`. Typical cases in a filter UI: - the filter drawer finishes its slide-out and code calls `trigger.focus()` to return focus to the chip that opened it; - a chip is removed after a request completes and code focuses its neighbour. If the ring is keyed only to `cdk-keyboard-focused`, a keyboard user who opened the drawer with Enter can return to a chip with no visible focus. The fix is to carry the origin forward: - record the origin when the drawer opens, for example from the trigger's `cdkFocusChange` or `monitor` stream; - restore with `focusMonitor.focusVia(trigger, origin)`, so a keyboard opener gets a keyboard ring and a mouse opener does not. Angular Material's drawer does exactly this when it hands focus back. - a `FocusKeyManager` passes `'program'` to each item's `focus(origin)` by default, so an item that forwards that value to `focusVia` would record arrow-key moves as programmatic; `setFocusOrigin('keyboard')` changes the value it passes. ## Detection modes The service's default **`IMMEDIATE`** mode attributes focus only to an interaction in the current or previous tick, so stale events do not leak into later focus changes. **`EVENTUAL`** attributes focus to the last interaction, however long ago. You choose with the `FOCUS_MONITOR_DEFAULT_OPTIONS` token and `FocusMonitorDetectionMode`. ## Practical notes - The observable emits inside Angular's zone, and only while it has subscribers. - Elements inside a shadow root are supported; the listeners attach to that root. - For purely visual cases, CSS `:focus-visible` is the browser's built-in heuristic; `FocusMonitor` is for when your code needs the origin or must restore it.
- What do the Angular CDK's cdkMonitorElementFocus and cdkMonitorSubtreeFocus directives differ in?`cdkMonitorElementFocus` counts only focus on the host element itself, like `monitor(el, false)`. `cdkMonitorSubtreeFocus` also counts focus on any descendant, like `monitor(el, true)`, which suits a chip with an inner remove button. Both emit the origin through `cdkFocusChange` and stop monitoring when destroyed.
- When would you switch FocusMonitor to EVENTUAL detection mode?In the default `IMMEDIATE` mode, only an interaction in the current or previous tick decides the origin. `EVENTUAL` uses the last interaction no matter how long ago, which helps when focus moves after a delay, for example after an animation. Provide it through `FOCUS_MONITOR_DEFAULT_OPTIONS` with `FocusMonitorDetectionMode.EVENTUAL`.
- FocusMonitor only reports whether an element is focused, not how.
- Calling element.focus() after a keypress handler always reports keyboard origin.
- Monitoring needs no cleanup because the service tracks element lifetimes.
- focusVia changes only the origin and does not move focus.
- FocusMonitor emits mouse for programmatic focus calls by default.