![](/img/trans.png)
[英]binding ngModel instead of value to a custom Angular directive for currency input
[英]In Angular2 ngModel value not updating on onBlur event of custom directive
我开发了一个自定义指令,用于修剪输入控件的值。 请找到相同的代码:
import { Directive, HostListener, Provider } from '@angular/core';
import { NgModel } from '@angular/forms';
@Directive({
selector: '[ngModel][trim]',
providers: [NgModel],
host: {
'(ngModelChange)': 'onInputChange($event)',
'(blur)': 'onBlur($event)'
}
})
export class TrimValueAccessor {
onChange = (_) => { };
private el: any;
private newValue: any;
constructor(private model: NgModel) {
this.el = model;
}
onInputChange(event) {
this.newValue = event;
console.log(this.newValue);
}
onBlur(event) {
this.model.valueAccessor.writeValue(this.newValue.trim());
}
}
问题是ngModel没有更新onBlur事件的值。 我试图修改onModelChange事件的值,但它不允许两个单词之间的空格(例如,ABC XYZ)
任何建议都会有所帮助。
请在onblur事件中添加以下代码行,而不是现有代码。它可以工作:
this.model.control.setValue(this.newValue.trim());
谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.