[英]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.