Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Update ngModel inside a custom directive at @HostListener('blur')

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!

like image 790
Mieden Avatar asked Oct 29 '22 21:10

Mieden


1 Answers

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]);
like image 177
Kali Avatar answered Nov 15 '22 07:11

Kali