Fabric.Cashmere icon indicating copy to clipboard operation
Fabric.Cashmere copied to clipboard

Add focus features to components

Open atkulp opened this issue 4 years ago • 0 comments

In standard HTML, there is the autofocus attribute. In Angular, due to component reuse, this isn't effective. It's easy enough to enable focus on show, but it would be nice to have this in the framework, especially to enable its use with composite components (like list selection).

Along with auto-focus, focus/blur events, focus capture, and anything else related to focus could be rolled into it as well.

Something as simple as the following can set focus as a starting point. Perhaps better than using setTimeout if possible! This naïve example also doesn't drill down into sub-elements of course.

@Directive({
  selector: '[hcSetFocus]',
})
export class SetFocusDirective implements OnInit {

  constructor(private el: ElementRef) {
    if (!el.nativeElement.focus) {
      throw new Error('Element does not accept focus.');
    }
  }

  ngOnInit(): void {
    setTimeout( () => {
        const input: HTMLInputElement = this.el.nativeElement as HTMLInputElement;
        input.focus();
    }, 100);
  }
}

atkulp avatar Feb 23 '21 20:02 atkulp