Angular 2 Input Directive Modifying Form Control Value

丶灬走出姿态 提交于 2019-12-04 00:25:04

This thrills me because I encountered this earlier and was left scratching my head.

Revisiting the issue, what you need to do is to change your this.control.valueAccessor.writeValue(upper) where the ControlValueAccessor is explicitly writing to the DOM element and not to the control itself to instead call

 this.control.control.setValue(upper);

which will change the value on the control and be correctly reflected both on the page and in the control's property. https://angular.io/docs/ts/latest/api/forms/index/ControlValueAccessor-interface.html

A ControlValueAccessor abstracts the operations of writing a new value to a DOM element representing an input control.

Here's a forked plunker: http://plnkr.co/edit/rllNyE07uPhUA6UfiLkU?p=preview

I was looking for something like this, but when I tried the code in my project I was getting errors on the line this.el.nativeElement.value.toUpperCase() as per the working example above given by @silentsod.

I amended the code to:

let str:string = this.control.value;
this.control.control.setValue(str.toUpperCase());

Here's a forked plunker: http://plnkr.co/edit/uf6udp7mQYmnKX6hGPpR?p=preview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!