简体   繁体   中英

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!

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]);

I think the prober solution may be using custom form controls . However I never used them.

Firing this.change.emit(event); should do the thing and is working for me. The magic is that you emit the event and not the value and the changed value must be within event.target.value.

So for example

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

so you may like to try:

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

For detailed reading I figured this blog post as introduction into angular2 two way data binding very helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM