如何在角度分量中使用debounceTime?

时间:2018-06-07 10:42:52

标签: angular rxjs debounce

我的要求是以这样一种方式执行被动表单字段验证,即只有在用户停止输入后才会显示错误消息。

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

我正在寻找适用于反应形式的解决方案

2 个答案:

答案 0 :(得分:3)

使(或至少)一种方法可以随时动态删除和添加验证器。

在您的输入上,使用keydown绑定将在用户开始输入时删除验证器,并使用keyup绑定将通过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

答案 1 :(得分:0)

ionViewWillEnter(){ console.log("got in with id:" + this.core.getUserKey()) this.core.getDeviceId().subscribe(deviceId:string)=>{ console.log(deviecId) }) } 等待所提到的时间段,然后调用subscribe方法。例如; debounceTime将等待1秒钟。它是通过debounceTime(1000)实现的。

可以将其添加到任何订阅方法中。以下是工作示例

pipes

在您的模板中

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

// dynamic forms
import { FormGroup, FormControl, FormBuilder } from '@angular/forms';


@Component({
    selector: 'app-customer-form',
    templateUrl: './customer-form.component.html',
})
export class CustomerFormComponent implements OnInit {

    emailMessage : string;

    private validationMessages = {
        required: "Email field is required",
        email: "Please enter a valid Email"
    }

    customerForm: FormGroup;

    customer = new Customer();

    constructor(private fb: FormBuilder) { }

    ngOnInit() {
        this.customerForm = this.fb.group({
            emailAddress: ['',
                [
                    Validators.required,
                    Validators.email
                ]
            ]
        })

        const emailControl = this.customerForm.get('emailAddress');
        emailControl.valueChanges.pipe( debounceTime(1000) ).subscribe(
            value => this.setEmailMessage(emailControl)
        )
    }

    setEmailMessage( c: AbstractControl ) : void {
        this.emailMessage = '';

        if ( (c.touched || c.dirty) && c.errors ) {
            this.emailMessage = Object.keys(c.errors).map( key => this.validationMessages[key]).join(' ');
        }

    }

}