Angular 2输入指令修改表单控制值 [英] Angular 2 Input Directive Modifying Form Control Value
问题描述
我有一个简单的Angular 2指令,可修改文本框的输入值.请注意,我使用的是模型驱动"表单方法.
I have a simple Angular 2 directive that modifies the input value of a textbox. Note that i'm using the Model-Driven form approach.
@Directive({
selector: '[appUpperCase]'
})
export class UpperCaseDirective{
constructor(private el: ElementRef, private control : NgControl) {
}
@HostListener('input',['$event']) onEvent($event){
console.log($event);
let upper = this.el.nativeElement.value.toUpperCase();
this.control.valueAccessor.writeValue(upper);
}
}
dom会正确更新,但是每隔一次按键就会更新一次模型.看看 plnkr
The dom updates properly, however the model updates after every other keystroke. Take a look at the plnkr
推荐答案
这让我很激动,因为我较早就遇到了这个问题,任由挠头.
This thrills me because I encountered this earlier and was left scratching my head.
要重新讨论该问题,您需要做的是更改您的this.control.valueAccessor.writeValue(upper)
,其中ControlValueAccessor显式写入DOM元素,而不是控件本身以代替调用
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);
,它将更改控件上的值,并正确显示在页面和控件的属性中. https://angular.io/docs/ts/latest/api/forms/index/ControlValueAccessor-interface.html
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
ControlValueAccessor抽象写入新值的操作 到代表输入控件的DOM元素.
A ControlValueAccessor abstracts the operations of writing a new value to a DOM element representing an input control.
这是一个分叉的矮人: http://plnkr.co/edit/rllNyE07uPhUA6UfiLkU?p=preview
Here's a forked plunker: http://plnkr.co/edit/rllNyE07uPhUA6UfiLkU?p=preview
这篇关于Angular 2输入指令修改表单控制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!