【问题标题】:How to trigger validation input after debounce time in Angular2?如何在Angular2中的去抖动时间后触发验证输入?
【发布时间】:2016-05-18 14:56:41
【问题描述】:

我有一个带有“名称”控件的表单。

<div class="field">
  <label>Name</label>
  <input ngControl="name">
  <p *ngIf="name.pending">
    Fetching data from the server...
  </p>
  <div *ngIf="!name.valid && !name.pending"
    class="ui error message">Name is not valid</div>
</div>

使用 FormBuilder 构建控件,如下所示:

this.name = fb.control('', null, this.characterNameValidator.bind(this));

我创建了一个验证器:

characterNameValidator(control: Control) {
    let q = new Promise((resolve, reject) => {
        setTimeout(() => {
            if (this._characterService.isCharacterNameAlreadyExists(control.value)) {
                resolve({nameCharacterAlreadyExistsError: true});
            } else {
                resolve(null);
            }
        }, 1000)
    });

    return q;
}

在每次击键时,都会调用我的验证器。我正在寻找一种仅在去抖动时间后调用验证器的方法。

我尝试使用 valueChanges(),但我仅在调用特定服务而不是在验证的情况下理解。

编辑

手动管理验证来解决我的问题是个好主意吗?我没有将验证器置于我的控制之下,但我在 valueChanges 上手动设置了错误。

this.name = fb.control('');

this.name.valueChanges.debounceTime(400).subscribe(() => {
  this.characterNameValidator(this.name).then((validationResult => {
    this.name.setErrors(validationResult)
  }))
});

【问题讨论】:

标签: validation asynchronous angular


【解决方案1】:

获得你想要的东西的官方方法是在即将推出的功能中进行表单验证。

https://youtu.be/kM5QBOWrUVI?t=9m48s

但是,您可以通过订阅值更改并设置您自己的错误来手动去抖动验证。

testForm.controls['name'].valueChanges
.do(
    res => {
        if (res) {
            this.testForm.controls['name'].setErrors({loading: true});
        }
    }
)
.debounceTime(500)
.subscribe(
    res => {
        if (this.nameSub) {
            this.nameSub.unsubscribe();
            this.nameSub = null;
        }

        this.nameSub = this.http.get(apiURL + 'exist/?name=' + res).subscribe(
            exists => {
                this.testForm.controls['name'].setErrors({nameExists: true});
                this.nameSub.unsubscribe();
                this.nameSub = null;
            },
            error => {
                if (res) {
                    this.testForm.controls['name'].setErrors(null);
                }
                this.nameSub.unsubscribe();
                this.nameSub = null;
            }
        );
    },
    error => {}
);

【讨论】:

    【解决方案2】:

    请参阅 https://github.com/angular/angular/issues/1068 了解相关的未解决问题。

    如果您将控件的引用传递给验证器,您可以使用类似

    this.formGp.controls['numberFld'].updateValueAndValidity();
    

    来自https://stackoverflow.com/a/33377290/217408

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-03
      • 1970-01-01
      • 1970-01-01
      • 2017-01-22
      • 2013-03-10
      • 2019-03-23
      • 2016-08-23
      相关资源
      最近更新 更多