简体   繁体   English

Angular Reactive Forms:在值改变之前检测用户输入

[英]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:我知道您可以使用 Angular Reactive Forms 中的 valueChanges observable 来检测输入字段中的值是否已更改:

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然后验证对输入的更改值起作用

is there a way to subscribe when the user has pressed a key, before the value changes in the input?在输入中的值发生变化之前,有没有办法在用户按下某个键时进行订阅?

onkeyup event : onkeyup 事件:

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

EDIT :编辑 :

You need subscribe to event keyup on your AbstractControl elememnt .您需要在AbstractControl 元素上订阅事件keyup

see the stackblitz堆栈闪电战

You could also create a directive to access your element using ElementRef regarding what your requirements are.您还可以创建一个指令来使用ElementRef访问您的元素,了解您的要求是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM