shrewdbeans
shrewdbeans

Reputation: 12529

Angular Reactive Forms: Detect user input before the value changes

I know that you can use the valueChanges observable in Angular Reactive Forms to detect if a value in the input field has already changed:

inputControl.valueChanges.subscribe(() => {
    // fires when the input value has actually changed
});

However, is there a way to subscribe to an observable of when the user has pressed a key, before the value changes in the input?

I need to do this so I can apply dynamic validation, for example:

  1. User presses a key
  2. I need to know what that key is before I apply validation
  3. Validation then works on the changed value of the input

Upvotes: 1

Views: 2782

Answers (1)

Florian
Florian

Reputation: 1481

is there a way to subscribe when the user has pressed a key, before the value changes in the input?

onkeyup event :

 <input formControlName="yourcontrol" (keyup)="onKeyUp($event)">

EDIT :

You need subscribe to event keyup on your AbstractControl elememnt.

see the stackblitz

You could also create a directive to access your element using ElementRef regarding what your requirements are.

Upvotes: 2

Related Questions