Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Angular2 ngModel value not updating on onBlur event of custom directive

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.

like image 855
Binal Vekariya Avatar asked Dec 20 '16 09:12

Binal Vekariya


People also ask

How do I update my ngModel value?

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.

How do you use onBlur event in angular 8?

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.

What is onBlur event in angular?

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.


1 Answers

Please add below lines of code in onblur event instead of existing code.It would work:

this.model.control.setValue(this.newValue.trim());

Thanks!

like image 64
Jayakrishnan Avatar answered Oct 05 '22 20:10

Jayakrishnan