One of the most important thing when building custom form component is adding accessbility support.
The component should be focusable. we can achieve this by adding 'tabindex="0"':
<div tabindex="0" >
Add some css class for foucs:
<div [class.focus]="focused" tabindex="0" (focus)="onFocus($event)" (blur)="onBlur($event)" >
.stock-counter { & .focus { box-shadow: 0 1px 1px rgba(0, 0, 0, .6); } ... }
onFocus() { this.focused = true; this.onTouch(); } onBlur() { this.focused = false; this.onTouch(); }
Handle keydwon event with code:
<div [class.focus]="focused" tabindex="0" (keydown)="onKeyDown($event)" (focus)="onFocus($event)" (blur)="onBlur($event)" >
onKeyDown(event: KeyboardEvent) { const handler = { ArrowDown: () => this.decrement(), ArrowUp: () => this.increment() }; if(handler[event.code]) { event.preventDefault(); event.stopPropagation(); handler[event.code](); } }