0

I have a below demo app and trying to set the errors in custom validators why it is not setting.

Step: click on add users and type the value . On value changes , i have call the customer validator and set the error or return the error but it is not set.

demo: demos

import { Component, VERSION } from '@angular/core';
import { FormArray, FormBuilder, FormGroup ,AbstractControl,Validators} from '@angular/forms';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
   myForm: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.myForm = this.fb.group({
      email: '',
      users: this.fb.array([])
    })
  }

  get userForms() {
    return this.myForm.get('users') as FormArray
  }

  getColors(index) {
    return this.userForms.get([index, 'colors']) as FormArray;
  }

  addUser() {
    const userGroup = this.fb.group({
      user: [],
      colors: this.fb.array([])
    })

    userGroup.controls['user'].setValidators(this.validateMobileNo);

    this.userForms.push(userGroup);
  }

  deleteUser(i) {
    this.userForms.removeAt(i);
  }

  addColor(index: number) {
    const colorGroup = this.fb.group({
      color: []
    })

    this.getColors(index).push(colorGroup);
  }

  deleteColor(userIndex: number, colorIndex: number) {
    this.getColors(userIndex).removeAt(colorIndex)
  }




  validateMobileNo(controller: AbstractControl): { [key: string]: any } {        console.log(controller.value);



    console.log("Returning null");
    controller.setErrors({error: "ghhggh"});
    return {error: "ghhggh"};
  }
}
Mohamed Sahir
  • 2,482
  • 8
  • 40
  • 71

1 Answers1

0

When you add or remove a validator at run time, you must call updateValueAndValidity() for the new validation to take effect.

this.<formgroup>.updateValueAndValidity()

Calling specific control:

this.<formgroup>.control[<'controlname'>].updateValueAndValidity()
sunilbaba
  • 441
  • 2
  • 9
  • when doing that it is recursively called and browser hanged controller.updateValueAndValidity({onlySelf:true,emitEvent:false}); – Mohamed Sahir Jun 17 '20 at 19:06
  • https://stackblitz.com/edit/github-2mdrme-2qgzib?file=src/index.html pls try to change here if found any solution whole idea is in value change i have call the asynchronus validators and send a request to server and server validates the user enter value and send back the validationmessage that message i need to display in the ui. – Mohamed Sahir Jun 17 '20 at 19:13