Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 ngModel one character behind

I have an input field where I want to validate the input after each keystroke. Ultimately I'd like to validate it when they click outside of the input field (not sure which DOM event to use for this). The problem is that the input is "lagging" behind by one character.

For instance, if the user types in "a", then the ngModel variable it's mapped to equals "". when they type in "ab", the variable equals "a".

Partial code of create-item.component.ts

export class CreateItem {
  public item: Item;

  constructor() {
    this.item = new Item();
  }

  onCheckItemInput() {
    // validate input on each keystroke
  }
}

Input field of create-item.component.html

<input class="form-control" type="text" required [(ngModel)]="item.name"
  #spy pattern=".{3,255}" (input)="onCheckItemInput()">

What am I doing wrong?

like image 999
DankestMemes Avatar asked Sep 10 '26 14:09

DankestMemes


1 Answers

The blur event is fired whenever a user loses focus with an input element.

Example: User clicks outside the input box.

<input class="form-control" type="text" required [(ngModel)]="item.name"
#spy pattern=".{3,255}" (blur)="onCheckItemInput()">

I've created a simple plunker to demonstrate this

https://plnkr.co/edit/4wnanssu08WPRziMkh9d?p=preview

like image 108
Richard Hamilton Avatar answered Sep 13 '26 02:09

Richard Hamilton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!