title: Angular2 keyup event update ngModel cursor position jumps to end
body: <p>I am having an issue with an Angular2 directive that should do the following:</p>
  
  <ul>
  <li>Detect if the user enters '.' character.</li>
  <li>If the next char is also '.', remove the duplicate '.' and move the cursor position to after the '.' char</li>
  </ul>
  
  <p>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.</p>
  
  <p>The input:</p>
  
  <pre><code>&lt;input type="text" name="test" [(ngModel)]="testInput" testDirective/&gt;
  </code></pre>
  
  <p>The directive:</p>
  
  <pre><code> import {Directive, ElementRef, Renderer, HostListener, Output, EventEmitter} from '@angular/core';
  
  @Directive({
    selector: '[testDirective][ngModel]'
  })
  export class TestDirective {
  
  
    @Output() ngModelChange: EventEmitter&lt;any&gt; = 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 === '.' &amp;&amp;
        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;
  
      }
    }
  }
  </code></pre>
  
  <p>This works, except the cursor position jumps to the end. Removing the line:</p>
  
  <pre><code>this.ngModelChange.emit(val);
  </code></pre>
  
  <p>Fixes the issue and the cursor position is correct, however the model is not updated.</p>
  
  <p>Can anyone recommend a solution to this? Or maybe I am taking the wrong approach to the problem?</p>
  
  <p>Thanks</p>