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.
If we use two way binding syntax for ngModel the value will be updated. So the default (ngModelChange) function will update the value of ngModel property. i.e., user.Name . And the second (ngModelChange) will be triggered printing the user name value in the console.
you can easily use blur event in angular 6, angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13 and angular 14 application. When user will key up on input box field then trigger onBlurEvent() of angular component. we will use (change) attribute for call function.
onBlur is a javascript event, fired when the input element lost its focus. You can see my previous about Angular button click event example Other versions available: React onBlur event guide example. Vue js Blur event example.
Please add below lines of code in onblur event instead of existing code.It would work:
this.model.control.setValue(this.newValue.trim());
Thanks!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With