12

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

conor
  • 883
  • 5
  • 14
  • 25

3 Answers3

14

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;
});
Alexander Leonov
  • 4,694
  • 1
  • 17
  • 25
  • 1
    I can confirm that this does work, and the flickering is not very noticeable. It is an acceptable solution. However, I was hoping to find a solution without using setTimeout. – conor Dec 02 '16 at 13:47
  • However when i type fast, the cursor goes to previous positions and causes issue – Ragul Parani Oct 20 '20 at 10:29
7

You can change position of a cursor without setTimout() and flickering as suggested in accepted answer with setSelectionRange() like this:

this.el.nativeElement.setSelectionRange(position, position, 'none');

Example: stackblitz

metodribic
  • 1,561
  • 17
  • 27
  • 1
    Well, this seems to be the best solution. It works flawlessly while the accept solution doesn't (maybe this was not available at the time of writing). If you type too fast you are able to overcome the setTimeout and get unexpected behavior. – António Quadrado Oct 23 '18 at 10:25
  • 1
    It doesn't work for some reason to set *selectionStart* and *selectionEnd* so your suggestion was awesome. Not sure why the others don't work (they are read correctly and used as parameters for *setSelectionRange()* but **setting** a value to them doesn't push the stupid marker to the right position. – Konrad Viltersten May 05 '19 at 21:06
  • 1
    Does not work in Angular 8 for me, I still had to wrap the function in `setTimeout()`. – FullStackOverflowDev Oct 12 '19 at 13:42
  • 1
    @George I added [stackblitz](https://stackblitz.com/edit/angular-azos2i) to my answer where you can see this solution works in Angular 8 – metodribic Dec 04 '19 at 13:09
  • @metodribic I'm no longer working on that project so I can't test but it was being done from inside of a directive that did some other stuff including `ngModelChange.emit` so it could have been related to that. – FullStackOverflowDev Mar 02 '20 at 12:18
  • I am using Angular 6 and i faced this issue in Safari alone. This solution did not work for me – Ragul Parani Oct 20 '20 at 10:32
2

For my case, an acceptable solution without using setTimeout was to:

  1. Not update the model on keyup
  2. Update the model instead on focusout

    @HostListener('focusout') focusOut() {
      this.ngModelChange.emit(this.el.nativeElement.value);
    }
    
conor
  • 883
  • 5
  • 14
  • 25