I have a custom directive that only accepts number. When I input 1.2, it is good. But when I type only 1. I want to erase the inputted 1. on blur. I have tried several ways on how to set the value to empty string inside the onBlur
but still no luck at all. Here is the code snippet:
@Output() ngModelChange = new EventEmitter();
constructor(el: ElementRef, public model: NgControl){
//Instead of NgControl, I have also tried the NgModel but it did not work
this.el = el.nativeElement;
}
@HostListener('blur', ['$event']) onBlur($event){
if(isNaN(this.el.value.replace(/(,)/g, '')) || this.el.value[this.el.value.length - 1] === '.' || this.el.value[this.el.value.length - 1] === '-'){
this.el.value = '';
this.model.control.updateValue('');
this.model.viewToModelUpdate('');
this.ngModelChange.emit('');
}
}
This does erase the 1. in the input field. But when I print out the value of the ngModel
that holds the data, the value is 1
In that case, I want to set the ngModel value to empty string. How can I do that inside the blur?
Thank you!
You can create and trigger a change event on the element to tell angular to update the model value.
let event: Event = document.createEvent("Event");
event.initEvent('input', true, true);
Object.defineProperty(event, 'target', {value: this.el.nativeElement, enumerable: true});
this.renderer.invokeElementMethod(this.el.nativeElement, 'dispatchEvent', [event]);
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