我如何在angular2中去抖形式

Sha*_*mim 6 javascript observable angular2-forms angular

我经历了很多帖子,但没找到我要找的东西.

基本上,

我正在显示表单更改的用户验证.我的模板看起来像这样:

<div class="form-group"
      [class.error]="!loginForm.find('email').valid && loginForm.find('email').touched">
        <div class="input-wrapper">
          <input type ="email"
              class="form-control"
              id="email-input"
              placeholder="Email"
              formControlName="email">
        </div>  
        <div *ngIf="loginForm.controls['email'].dirty && !loginForm.controls['email'].valid"
          class="alert-msg">Email is invalid</div>
</div>
Run Code Online (Sandbox Code Playgroud)

而且,看看其他帖子,我的TS去抖形式是这样的:

this.loginForm.valueChanges.debounceTime(500).subscribe(form => {
  console.log(form, this.loginForm);
});
Run Code Online (Sandbox Code Playgroud)

现在,控制台日志实际上是在反弹.但是,验证消息不会消除.它直接显示消息.

有没有办法克服这个问题?

谢谢,为了停下来,

P. *_*ney 5

I believe the debounceTime will only affect the code you have in the response form => { ... }. So what you could do is set the validation there:

private loginFormIsValid:boolean;
private emailIsNotValid:boolean;

ngOnInit() {
    this.loginForm.valueChanges.debounceTime(500).subscribe(form => {
        this.loginFormIsValid = !loginForm.find('email').valid 
            && loginForm.find('email').touched;
        this.emailIsNotValid = loginForm.controls['email'].dirty 
            && !loginForm.controls['email'].valid;
        console.log(form, this.loginForm);
    });
}
Run Code Online (Sandbox Code Playgroud)

...And then you would use it in you template as follows:

<div class="form-group" [class.error]="!loginFormIsValid">
    <div class="input-wrapper">
      <input type ="email"
          class="form-control"
          id="email-input"
          placeholder="Email"
          formControlName="email">
    </div>  
    <div *ngIf="emailIsNotValid"
      class="alert-msg">Email is invalid</div>
</div>
Run Code Online (Sandbox Code Playgroud)

You can take a look at a post on debouncing, it's a good example.