角反应形式添加自定义Validation onBlur

时间:2019-02-15 05:05:44

标签: angular

我正在尝试正确设置OnBlur语法,但这使我难以理解。

export class AppComponent  {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      published: true,
      credentials: this.fb.array([]),
    });
  }

  addCreds() {
    const creds = this.form.controls.credentials as FormArray;
    creds.push(this.fb.group({
      username: ['', [this.isNameDuplicate(this.form)]],
      password: '',
    }));
  }

  isNameDuplicate(form:FormGroup): ValidatorFn {
    return (c: AbstractControl): { [key: string]: boolean } | null => {
    const userNames = this.form.get("credentials").value;
    console.log(userNames);
    const names = userNames.map(item=> item.username.trim());
    const hasDuplicate = names.some(
    (name, index) => names.indexOf(name, index + 1) != -1
  );

     if (hasDuplicate) {
       console.log(hasDuplicate);
       return { duplicate: true };
     }

     return null;
    }
  } 
}

我必须确保isNameDuplicate验证程序触发onb​​lur,但是语法使我难以理解。

请给我一些帮助。

我的尝试

addCreds() {
    const creds = this.form.controls.credentials as FormArray;
    creds.push(this.fb.group({
      username: ['', {
      validators:[this.isNameDuplicate(this.form)],
      updateOn:'blur'}],
      password: '',
    }));
  }

但是我收到一条错误消息,说组件上不存在isNameDuplicate。

2 个答案:

答案 0 :(得分:0)

我设法使用

addCreds() {
    const creds = this.form.controls.credentials as FormArray;
    creds.push(this.fb.group({
      username: ['', {
      validators:[this.isNameDuplicate(this.form)],
      updateOn:'blur'}],
      password: '',
    }));
  }

答案 1 :(得分:0)

在组件的HTML文件中,用户模糊事件如下所示:-

<input (blur)="callSOmeFunction()">


callSOmeFunction(){
sampleForm.valid
}