[Angular HTML] Overwrite input value, String.fromCharCode & input.selectionStart

  @HostListener('keydown', ['$event', '$event.keyCode'])
  onKeyDown($event: KeyboardEvent, keyCode) {

    if(keyCode !== TAB) {
      $event.preventDefault();
    }

    // get value for the key
    const val = String.fromCharCode(keyCode);
    // get position
    const cursorPos = this.input.selectionStart;

    overWriteCharAtPosition(this.input, val, cursorPos);
  }

export const overWriteCharAtPosition = (
  input: HTMLInputElement,
  val: any,
  position: number
) => {
  const currentValue = input.value;
  input.value = currentValue.slice(0, position) + val + currentValue.slice(position+1);
};
原文地址:https://www.cnblogs.com/Answer1215/p/7226834.html