简体   繁体   中英

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. But we have a huge codebase and I was thinking maybe with @Hostlistener would be able to change the value.

@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.

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.

For that we can use the directive and model service

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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