简体   繁体   English

在Angular2中,ngModel值不会更新onBlur自定义指令事件

[英]In Angular2 ngModel value not updating on onBlur event of custom directive

I have developed a custom directive which trims value of input controls. 我开发了一个自定义指令,用于修剪输入控件的值。 Please find the code for the same: 请找到相同的代码:

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());    
 }
}

The problem is ngModel not updating value on onBlur event. 问题是ngModel没有更新onBlur事件的值。 I tried to trim value on onModelChange event but it doesn't allow space between two words(eg, ABC XYZ) 我试图修改onModelChange事件的值,但它不允许两个单词之间的空格(例如,ABC XYZ)

Any suggestion would be helpful. 任何建议都会有所帮助。

Please add below lines of code in onblur event instead of existing code.It would work: 请在onblur事件中添加以下代码行,而不是现有代码。它可以工作:

this.model.control.setValue(this.newValue.trim());

Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM