Bin*_*iya 7 html javascript angular2-directives angular
我开发了一个自定义指令,用于修剪输入控件的值.请找到相同的代码:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
问题是ngModel没有更新onBlur事件的值.我试图修改onModelChange事件的值,但它不允许两个单词之间的空格(例如,ABC XYZ)
任何建议都会有所帮助.
请在onblur事件中添加以下代码行,而不是现有代码。它将起作用:
this.model.control.setValue(this.newValue.trim());
Run Code Online (Sandbox Code Playgroud)
谢谢!