我有一个简单的 Angular 2 指令,用于修改文本框的输入值。请注意,我使用的是模型驱动表单方法。
@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
最佳答案
这让我很激动,因为我之前遇到过这个问题并且摸不着头脑。
重新审视这个问题,您需要做的是更改 this.control.valueAccessor.writeValue(upper)
,其中 ControlValueAccessor 显式写入 DOM 元素而不是控件本身而是调用
this.control.control.setValue(upper);
这将更改控件上的值并正确反射(reflect)在页面和控件的属性中。 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.
这是一个 fork 的插件:http://plnkr.co/edit/rllNyE07uPhUA6UfiLkU?p=preview
关于Angular 2 输入指令修改表单控件值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40682717/