Answer the question
In order to leave comments, you need to log in
keyup event in Angular 2 directive?
Why does this condition not work if the text in the input field is less than the one specified in limitTo:
@HostListener('keyup') ngOnChanges() {
if(this.el.nativeElement.value.length <= this.limitTo) {
return false
}
}
@HostListener('keyup', ['$event']) onKeyUp(event) {
if (this.el.nativeElement.value.length + 1 <= this.limitTo) {
e.preventDefault();
}
return;
}
Answer the question
In order to leave comments, you need to log in
The `keyup` event fires after the `value` has changed, so resetting it does nothing.
If the task needs to prohibit deletion of characters if the string is shorter than some limit, then I would suggest this option: save the value before changes, and check validity on `change` and if something is wrong, then roll back the value.
`change` - because the user can change it with the mouse, for example, cut it through the context menu.
Working demo: https://stackblitz.com/edit/angular-85uyuj
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question