我的要求是以以下方式执行响应式(Reactive)表单字段验证:仅在用户停止键入后才显示错误消息。

如何使用 react 形式和Rxjs debounceTime完成此操作?

我正在寻找适用于响应式(Reactive)表格的解决方案

最佳答案

使它生效的(或至少一种)方法是在运行时动态删除并添加验证器。
在您的输入上,使用keydown绑定(bind)(当用户开始键入时将剥离验证器)和keyup绑定(bind)(将通过debounceTime管道运行,然后重新应用验证器)(但仅在经过指定的反跳时间之后) 。
代码在这里:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

@Component({
    selector: 'form-component',
    template: `
        <form [formGroup]="formGroup">
          <input type="text" formControlName="name" (keyup)="onKeyUp()" (keydown)="onKeyDown()" [ngClass]="{ 'invalid': formGroup.controls.name.invalid }">
        </form>
      `,
    styles: [
        '.invalid { border-color: red; color: red; }'
    ]
})
export class FormComponent implements OnInit {

    formGroup: FormGroup;
    subject: Subject<any> = new Subject();

    constructor(private formBuilder: FormBuilder) {}

    ngOnInit(): void {
        this.formGroup = this.formBuilder.group({
            name: [ '' ]
        });

        // Subscribe to the subject, which is triggered with each keyup
        // When the debounce time has passed, we add a validator and update the form control to check validity
        this.subject
            .pipe(debounceTime(500))
            .subscribe(() => {
                    this.formGroup.controls.name.setValidators([ Validators.minLength(5) ]);
                    this.formGroup.controls.name.updateValueAndValidity();
                }
            );
    }

    onKeyUp(): void {
        this.subject.next();
    }

    onKeyDown(): void {
        // When the user starts to type, remove the validator
        this.formGroup.controls.name.clearValidators();
    }

}
而StackBlitz在这里:https://stackblitz.com/edit/debounce-validator

关于angular - 如何在 Angular 组件中使用debounceTime?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50739211/

10-11 13:32