简体   繁体   English

用Javascript更改输入值后如何强制Angular 2 [(ngModel)]更改?

[英]How to force Angular 2 [(ngModel)] change after changing input value with Javascript?

I am trying to replace Japanese half-width characters to full-width characters. 我正在尝试将日文半角字符替换为全角字符。

ウ -> ウ ウ->ウ

So whenever a user types in half width, we have to convert to full width automatically. 因此,无论何时用户输入半角,我们都必须自动转换为全角。

Obvious solution would be to design a directive to change the ngModel on keypress. 显而易见的解决方案是设计一个指令来更改按键上的ngModel。 But we have a huge codebase and I was thinking maybe with @Hostlistener would be able to change the value. 但是我们有一个庞大的代码库,我在想也许@Hostlistener可以更改该值。

@HostListener('document:keyup', ['$event']) onKeydownHandler(event) {
   if (event.target.hasAttribute('type')
       && event.target.attributes['type'].value === 'text') {

    event.target.value = this.changeToFullWidth(event, event.target.value);

  }
}

However with this [(ngModel)] is always one character behind and I know this is because I am touching the HTML element directly. 但是,使用此[(ngModel)]总是后面有一个字符,我知道这是因为我直接触摸HTML元素。

Is there a way to do this ? 有没有办法做到这一点 ? Or will I have to go harder approach of adding directive to each input tag in whole project? 还是我不得不采取更艰辛的方法,在整个项目中向每个输入标签添加指令?

At last I was able to trigger model change following way: 最后,我能够通过以下方式触发模型更改:

targetElement.dispatchEvent(new Event('input'), {bubbles: true});

But found out that it doesn't work in Edge for CKEditor. 但是发现它在Edge for CKEditor中不起作用。

For that we can use the directive and model service 为此,我们可以使用指令和模型服务

...
constructor(
        ...
        private model:NgModel,
        ...
    ){
...
onInputChange($event){
...
   this.model.valueAccessor.writeValue(this.changeText(modelValue));
...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM