如何在角度组件中使用 debounceTime? [英] How to use debounceTime in an angular component?

查看:17
本文介绍了如何在角度组件中使用 debounceTime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求是执行响应式表单字段验证,以便仅在用户停止输入后显示错误消息.

My requirement is to perform reactive form field validations in such a way that the error messages are displayed only after the user stops typing.

如何使用响应式表单和 Rxjs debounceTime 来完成此操作?

How can I accomplish this using reactive forms and Rxjs debounceTime?

我正在寻找一种适用于响应式表单的解决方案

I'm looking for a solution that works with Reactive forms

推荐答案

实现此功能的(或至少是一种)方法是随时动态删除和添加验证器.

The (or at least a) way to get this to work is to dynamically remove and add your validators as you go.

在您的输入上,使用 keydown 绑定,当用户开始输入时,它会去除验证器,以及一个 keyup 绑定,它将运行一个 debounceTime管道,然后重新应用验证器(但必须在指定的去抖动时间过后).

On your input(s), use a keydown binding that will strip away validators when the user starts to type, and a keyup binding that will run through a debounceTime pipe and then reapply the validators (but only after the specified debounce time has passed).

代码在这里:

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

And StackBlitz here: https://stackblitz.com/edit/debounce-validator

这篇关于如何在角度组件中使用 debounceTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆