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

I have a custom directive that only accepts a number. When I enter 1.2, that’s good. But when I print only 1. I want to erase the entered 1. to blur. I tried several ways to set the value to an empty string inside onBlur , but still no luck. 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 erases 1. in the input field. But when I print the ngModel value in which the data is stored, the value is 1

In this case, I want to set the ngModel value to an empty string. How can I do this inside the blur?

Thanks!

+5
source share
2 answers

You can create and fire a change event on an 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]); 
+1
source

I think the prober solution can use custom control forms . However, I have never used them.

Shooting this.change.emit(event); should do what works and works for me. The magic is that you select the event and not the value , but the changed value should be within the event.target.value.

So for example

 let onChangeCallback = (e) => { console.log("change", e ); this.ngModelChange.emit(e); this.change.emit(e) }; 

so you can try:

 $event.target.value = "", this.change.emit($event); 

For a detailed reading, I decided that this blog post as an introduction to angular2 two-way data binding is very useful.

+1
source

All Articles