Angular 2 输入指令修改表单控件值
Angular 2 Input Directive Modifying Form Control Value
我有一个简单的 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);
这将更改控件上的值并正确反映在页面和控件的 属性 中。
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.
这是一个分叉的插件:http://plnkr.co/edit/rllNyE07uPhUA6UfiLkU?p=preview
我一直在寻找类似的东西,但是当我在我的项目中尝试代码时,根据@silentsod 给出的上述工作示例,我在 this.el.nativeElement.value.toUpperCase() 行遇到错误。
我将代码修改为:
let str:string = this.control.value;
this.control.control.setValue(str.toUpperCase());
这是一个分叉的插件:
http://plnkr.co/edit/uf6udp7mQYmnKX6hGPpR?p=preview
我有一个简单的 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);
这将更改控件上的值并正确反映在页面和控件的 属性 中。 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.
这是一个分叉的插件:http://plnkr.co/edit/rllNyE07uPhUA6UfiLkU?p=preview
我一直在寻找类似的东西,但是当我在我的项目中尝试代码时,根据@silentsod 给出的上述工作示例,我在 this.el.nativeElement.value.toUpperCase() 行遇到错误。
我将代码修改为:
let str:string = this.control.value;
this.control.control.setValue(str.toUpperCase());
这是一个分叉的插件: http://plnkr.co/edit/uf6udp7mQYmnKX6hGPpR?p=preview