Skip to content

Instantly share code, notes, and snippets.

@Ksisu
Last active September 14, 2020 07:36
Show Gist options
  • Save Ksisu/0eb2fed131cd7d1504cb59421c4c5a6c to your computer and use it in GitHub Desktop.
Save Ksisu/0eb2fed131cd7d1504cb59421c4c5a6c to your computer and use it in GitHub Desktop.
Angular enable tabulator on input field
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[enableTab]'
})
export class EnableTabDirective {
constructor(private elementRef: ElementRef) {
}
@HostListener('keydown.tab', [ '$event' ])
onTabKeyDown(event) {
event.preventDefault();
const value = this.elementRef.nativeElement.value;
const start = this.elementRef.nativeElement.selectionStart;
const end = this.elementRef.nativeElement.selectionEnd;
this.elementRef.nativeElement.value = value.substring(0, start) + '\t' + value.substring(end);
this.elementRef.nativeElement.selectionStart = start + 1;
this.elementRef.nativeElement.selectionEnd = this.elementRef.nativeElement.selectionStart;
event.preventDefault();
const val = this.elementRef.nativeElement.value;
const start = this.elementRef.nativeElement.selectionStart;
const end = this.elementRef.nativeElement.selectionEnd;
this.elementRef.nativeElement.value = val.substring(0, start) + '\t' + val.substring(end);
this.elementRef.nativeElement.selectionStart = this.elementRef.nativeElement.selectionEnd = start + 1;
const evt = new Event('input', {bubbles: true, cancelable: false});
this.elementRef.nativeElement.dispatchEvent(evt);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment