I am having problem with Angular's (keypress). I want to store event.target.value as variable but if I write 'pizza' in the input field, it stores 'pizz'. How can I store the 'pizza' anyway?
Thanks for the help.
HTML:
<input type="text" (keypress)="onKeypressEvent($event)" />
Typescript:
storedValue: string = '';
onKeypressEvent(event: any) {
console.log(event);
console.log(event.target.value);
this.storedValue = event.target.value;
if (event.key === 'Enter') {
this.onSubmit();
}
}
Working example on StackBlitz: https://stackblitz.com/edit/angular-ivy-ddyqbx?file=src/app/app.component.html,src/app/app.component.ts
SOLVED
I added two way binding to my input field and it solved the problem. Maybe this is not "the best" practice, but it solved the problem.
<input type="text" (input)="keyValue(event)" (keypress)="onKeypressEvent($event)" />
onKeypressEventOccupation(event: any) {
if (event.key === 'Enter') {
this.onSubmit();
}
}
keyValue(event: any) {
this.storedValue = event.target.value;
}
CodePudding user response:
as per doc , keypress will sent previous character of a character which you are pressing at moment. So that is reason you always see characters except most recent character in your event.target.value
.
e.g. -> you typed pizza
, event.target.value
will have pizz
.
As most recent character is yet to pressed down by any new input.
As mentioned in comments, you can use keyup
or input
for displaying all characters as soon as you typed it.