1

In an html form, When you use tab to go on next input it select all the content by default, How to unselect it?

Nicolas
  • 2,684
  • 1
  • 16
  • 22

3 Answers3

3

Set #myInput and bind the focus event <input #myInput (focus)="onFocus()">

@ViewChild('myInput') myInput: ElementRef<HTMLInputElement>;

and

onFocus() {
    setTimeout(() => {
      this.myInput.nativeElement.setSelectionRange(0,0);
    }, 0)
}

The timeout is required because when you select an input with the tab key, the text is automatically selected right after the focus event.

Kraken
  • 68
  • 6
3

Just set target.selectionEnd to 0 on focus event

<input (focus)="unselectOnFocus($event)">
unselectOnFocus(event: Event): void {
  event.target.selectionEnd = 0;
}
0

For setting the elements as unselectable, you can use tabindex = -1 attribute in the input element like following-

<input tabindex='-1'>

A negative value (usually tabindex="-1") means that the element is not reachable via sequential keyboard navigation, but could be focused with Javascript or visually by clicking with the mouse.

You can check more about this here- tabindex MDN guide

Hope this will help you.

praveen kaushik
  • 116
  • 1
  • 5