如何正确应对 Angular FormGroup 的变化?

问题描述 投票:0回答:1

与我作为例子看到的其他表单或我项目中的其他表单不同,我需要在没有任何提交操作的情况下对更改做出反应,并即时将新值应用到我的应用程序。

this.form.get('my_input').valueChanges.pipe(
  debounceTime(100),
  tap(() => this.form.markAllAsTouched()),
  filter(() => this.form.valid),
  tap(() => {
    // Do some stuff on other properties and labels
  })
).subscribe();

代码的灵感来自示例,但我没有设法执行任何操作,除非我将

pipe
和 RxJS 运算符删除到:

this.form.get('my_input').valueChanges.subscribe(newValue => {
  // Do some stuff on other properties and labels
};

我仍然无法准确理解处理表单更改的好方法以及在表单上使用管道的好方法。
我需要验证,显示输入错误,防止用户输入错误字符等,但没有任何提交按钮。第二个似乎有效的代码消除了角形式的那些特征......

编辑:表单已经声明了验证器,但它们不会阻止用户即时输入:

[Validators.required, Validators.pattern('\d+'), Validators.min(1)]

angular rxjs angular-forms
1个回答
3
投票

是的,管道很棘手。

如果你想验证并显示错误,我建议你使用表单控件中包含的验证器:

这是一个完整的教程https://angular.io/guide/form-validation

然后,使用简单的订阅方式执行其他不同的功能

© www.soinside.com 2019 - 2024. All rights reserved.