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

查看:195
本文介绍了如何在角度组件中使用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天全站免登陆