Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
792 views
in Technique[技术] by (71.8m points)

rxjs - How to use debounceTime in an angular component?

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.

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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).

Code here:

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();
    }

}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...