Angular 2 输入指令修改表单控件值 [英] Angular 2 Input Directive Modifying Form Control Value

查看:22
本文介绍了Angular 2 输入指令修改表单控件值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 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.

这是一个分叉的 plunker:http://plnkr.co/edit/rllNyE07uPhUA6UfiLkU?p=preview

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

这篇关于Angular 2 输入指令修改表单控件值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆