Angular2 keyup事件更新ngModel光标位置跳到结束 [英] Angular2 keyup event update ngModel cursor position jumps to end

查看:128
本文介绍了Angular2 keyup事件更新ngModel光标位置跳到结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了有关Angular2指令的问题,该指令应执行以下操作:

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

  • 检测用户是否输入.".字符.
  • 如果下一个字符也是.",请删除重复的.".并将光标位置移到."之后字符

我已经完成了上述工作,但是,将其与ngModel结合使用时,每次更新模型时,光标位置都会跳到末尾.

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.

输入:

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

指令:

 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?

谢谢

推荐答案

您需要在setTimeout()调用中包装以下几行.原因是您需要给浏览器一些时间来渲染新值,然后才更改光标位置,该光标位置在渲染新值后会重置.不幸的是,这会引起一些闪烁,但是我找不到其他方法使之工作.

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;
});

这篇关于Angular2 keyup事件更新ngModel光标位置跳到结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆