K
K
Konstantin2018-07-29 20:57:27
Angular
Konstantin, 2018-07-29 20:57:27

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
    }
  }

Here, for some reason, return false does not work;
Tried this option:
@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

1 answer(s)
S
Sasha Novik, 2018-08-12
@Junart1

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 question

Ask a Question

731 491 924 answers to any question