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.
Please add below lines of code in onblur event instead of existing code.It would work:
Thanks!