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

1.4k Views Asked by At

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(e.g., ABC XYZ)

Any suggestion would be helpful.

1

There are 1 best solutions below

0
On BEST ANSWER

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

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

Thanks!