Angular 2 change event on every keypress
The change event is only called after the focus of the input has changed. How can I make it so that the event fires on every keypress?
<input type="text" [(ngModel)]="mymodel" (change)="valuechange($event)" />
{{mymodel}}
The second binding changes on every keypress btw.
Solution 1:
I just used the event input and it worked fine as follows:
in .html file :
<input type="text" class="form-control" (input)="onSearchChange($event.target.value)">
in .ts file :
onSearchChange(searchValue: string): void {
console.log(searchValue);
}
Solution 2:
Use ngModelChange
by breaking up the [(x)]
syntax into its two pieces, i.e., property databinding and event binding:
<input type="text" [ngModel]="mymodel" (ngModelChange)="valuechange($event)" />
{{mymodel}}
valuechange(newValue) {
mymodel = newValue;
console.log(newValue)
}
It works for the backspace key too.
Solution 3:
The (keyup) event is your best bet.
Let's see why:
- (change) like you mentioned triggers only when the input loses focus, hence is of limited use.
- (keypress) triggers on key presses but doesn't trigger on certain keystrokes like the backspace.
- (keydown) triggers every time a key is pushed down. Hence always lags by 1 character; as it gets the element state before the keystroke was registered.
- (keyup) is your best bet as it triggers every time a key push event has completed, hence this also includes the most recent character.
So (keyup) is the safest to go with because it...
- registers an event on every keystroke unlike (change) event
- includes the keys that (keypress) ignores
- has no lag unlike the (keydown) event