Closed
Description
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
toCdkMonitorFocus
directive - Memoize and expose the focus state, eg. add new readonly
focusOrigin: FocusOrigin
orfocused: 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.