Angular2 keyup event update ngModel cursor position jumps to end

conor picture conor · Dec 2, 2016 · Viewed 14k times · Source

I am having an issue with an Angular2 directive that should do the following:

  • Detect if the user enters '.' character.
  • If the next char is also '.', remove the duplicate '.' and move the cursor position to after the '.' char

I have the above working, however, when using this in combination with ngModel, the cursor position jumps to the end every time the model is updated.

The input:

<input type="text" name="test" [(ngModel)]="testInput" testDirective/>

The directive:

 import {Directive, ElementRef, Renderer, HostListener, Output, EventEmitter} from '@angular/core';

@Directive({
  selector: '[testDirective][ngModel]'
})
export class TestDirective {


  @Output() ngModelChange: EventEmitter<any> = new EventEmitter();

  constructor(private el: ElementRef,
    private render: Renderer) { }

  @HostListener('keyup', ['$event']) onInputChange(event) {
    // get position
    let pos = this.el.nativeElement.selectionStart;

    let val = this.el.nativeElement.value;

    // if key is '.' and next character is '.', skip position
    if (event.key === '.' &&
      val.charAt(pos) === '.') {

      // remove duplicate periods
      val = val.replace(duplicatePeriods, '.');

      this.render.setElementProperty(this.el.nativeElement, 'value', val);
      this.ngModelChange.emit(val);
      this.el.nativeElement.selectionStart = pos;
      this.el.nativeElement.selectionEnd = pos;

    }
  }
}

This works, except the cursor position jumps to the end. Removing the line:

this.ngModelChange.emit(val);

Fixes the issue and the cursor position is correct, however the model is not updated.

Can anyone recommend a solution to this? Or maybe I am taking the wrong approach to the problem?

Thanks

Answer

Alexander Leonov picture Alexander Leonov · Dec 2, 2016

You need to wrap following lines in setTimeout() call. The reason is that you need to give browser time to render new value and only then change cursor position which gets reset after new value rendering. Unfortunately, this will cause a little flickering, but I wasn't able to find any other way to make it work.

setTimeout(() => {
  this.el.nativeElement.selectionStart = pos;
  this.el.nativeElement.selectionEnd = pos;
});