如何将额外的参数传递给Angular中的异步验证器(被动形式)?

时间:2017-08-09 19:24:31

标签: angular angular-reactive-forms angular-validation

我有以下异步验证器。如果我想将它用于反应形式,我必须将其作为第3个参数传递给

slug: [null, [Validators.required], [CustomValidators.slug]],

如何将额外的参数传递给验证器?

import {FormControl} from "@angular/forms";

interface IValidation {
    [key: string]: boolean;
}

export class CustomValidators {

static slug(control: FormControl) {
    const q = new Promise<IValidation>((resolve, reject) => {
        setTimeout(() => {
            if (control.value === 'TEST') {
                resolve({'duplicated': true});
            } else {
                resolve(null);
            }
        }, 1000);
    });
    return q;
}
}

如果我用它

slug:[null,[Validators.required],[CustomValidators.slug(&#39; string param&#39;)]],

问题是第一个参数是控件。

1 个答案:

答案 0 :(得分:1)

写下你的验证:

static slug(param: string) {
  return (control: FormControl) => {
    const q = new Promise<IValidation>((resolve, reject) => {
      setTimeout(() => {
        if (control.value === 'TEST') {
          resolve({'duplicated': true});
        } else {
          resolve(null);
        }
      }, 1000);
    });
    return q;
  };
}