Skip to content

feat(cdk/a11y): expose current focus state from cdkMonitorElementFocus & cdkMonitorSubtreeFocus #25423

Closed
@EmmanuelRoux

Description

@EmmanuelRoux

Feature Description

It would be very helpful to be able to export cdkMonitorElementFocus & cdkMonitorSubtreeFocus directives to read current focus state from template.

This requires:

  • Add exportAs to CdkMonitorFocus directive
  • Memoize and expose the focus state, eg. add new readonly focusOrigin: FocusOrigin or focused: boolean field(s)

I would be pleased to suggest a PR.

Use Case

Use case is to be able to easily check the focus state of an element to adapt other parts of the UI (eg. showing/hiding other elements...).

Example:

<div cdkMonitorSubtreeFocus #focusMonitor="cdkMonitorElementFocus ">
  <input type="text" />
  <input type="text" />
  <button type="button">Button 1</button>

  <!-- Following button should be displayed only when any of above inputs or button is focused -->
  <button *ngIf="focusMonitor.focused" type="button" (click)="doSomething()">Button 2</button>
</div>

My current alternative is to declare a custom directive like below:

@Directive({
  selector: '[cdkMonitorElementFocus], [cdkMonitorSubtreeFocus]', // Match existing CDK directives, or add another selector
  exportAs: 'myFocusMonitor',
})
export class MonitorFocusDirective {
  focused = false;

  @HostListener('cdkFocusChange', ['$event'])
  onFocusChange(origin: FocusOrigin): void {
    this.focused = !!origin;
  }
}

Note: existing cdkMonitorElementFocus/cdkMonitorSubtreeFocus directive already apply some css classes, which can be used to hide the element. But a css-only solution is not suitable for all scenarios.

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureThis issue represents a new feature or feature request rather than a bug or bug fixneeds triageThis issue needs to be triaged by the team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions