简体   繁体   中英

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. I tried to trim value on onModelChange event but it doesn't allow space between two words(eg, ABC XYZ)

Any suggestion would be helpful.

Please add below lines of code in onblur event instead of existing code.It would work:

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

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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