簡體   English   中英

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

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM