0

I am trying to get the OnBlur syntax correct but it is eluding me.

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;
    }
  } 
}

I have to make sure that the isNameDuplicate validator fires onblur but the syntax is eluding me.

Can i get some help please.

My try

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

But i get an error saying isNameDuplicate does not exist on the component.

jhon.smith
  • 1,963
  • 6
  • 30
  • 56
  • Checkout " 'blur' " in https://angular.io/api/forms/AbstractControl#updateOn – racraman Feb 15 '19 at 05:50
  • also duplicate of https://stackoverflow.com/questions/33866824/angular2-formcontrol-validation-on-blur – racraman Feb 15 '19 at 05:51
  • Hi from the docs it is not clear to me racraman and also in the duplicate SO post the syntax is different i am using formBuilder not the formControl syntax – jhon.smith Feb 15 '19 at 05:57
  • you don't pass this.form as parameter in function this.isNameDuplicate().. – Dharan Feb 15 '19 at 06:22

2 Answers2

0

I managed to get it to work using

addCreds() {
    const creds = this.form.controls.credentials as FormArray;
    creds.push(this.fb.group({
      username: ['', {
      validators:[this.isNameDuplicate(this.form)],
      updateOn:'blur'}],
      password: '',
    }));
  }
jhon.smith
  • 1,963
  • 6
  • 30
  • 56
0

In your component's HTML file user blur event like follows:-

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


callSOmeFunction(){
sampleForm.valid
}
siddharth shah
  • 1,139
  • 1
  • 9
  • 17