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()" />
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
Example without NgModel
<input type="text" (keyup)="onKeyPress($event)">
onKeyPress($event) {
console.log($event.target.value)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With