Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 get entire input value on keypress or keydown

I may be going about this wrong because I am doing something simple but my solutions are very bug prone.

All I want to do is execute a filter on a 3rd party component when input text changes (on key down).

first approach that didn't work:

<input type="text" placeholder="Name Fitler" [(ngModel)]="NameFilter" (keydown)="keyDown($event)" />

the problem is that key down executes before NameFilter is updated with latest characters, so my filter is one character behind

second approach that didn't work

keyDown(event:KeyboardEvent){
    var input = <HTMLInputElement>event.srcElement; 
    this.NameFilter = input.value + event.key; // <-- have to add the latest character
    this.filterChanged();
}

this sort of works but is bug prone. input.value doesn't have the latest character so i am adding it but would need to worry about odd keys etc. I'd like to avoid keyCode filtering if i can.

Is there another event ? or better way to get that value including the latest key down? (i do not want to wait for key up, or enter)

update this works perfectly

<input type="text" placeholder="Name Fitler" [(ngModel)]="NameFilter" (ngModelChange)="filterChanged()" />
like image 739
Sonic Soul Avatar asked Dec 08 '16 16:12

Sonic Soul


2 Answers

You can use (ngModelChange)="...".

(ngModelChange)="keyDown($event)"

ngModelChange is emitted when [(ngModel)]="NameFilter" updates NameFilter.

The () inside [ngModel]) is just a shorter form (syntactic sugar) for

[ngModel]="NameFilter" (ngModelChange)="NameFilter = $event"

See also https://angular.io/docs/ts/latest/guide/template-syntax.html#!#two-way

like image 59
Günter Zöchbauer Avatar answered Nov 17 '22 10:11

Günter Zöchbauer


Example without NgModel

<input type="text" (keyup)="onKeyPress($event)">
onKeyPress($event) {
    console.log($event.target.value)
}
like image 1
Erick Cisneros Avatar answered Nov 17 '22 10:11

Erick Cisneros