Angular Reactive Form set validator with Enter the data.



 public morningForm:FormGroup;

 constructor(public fb: FormBuilder) { }
 ngOnInit() {
 this.morningForm = this.fb.group({
      'country': [''],
      'city' : [''],
      'phone': ['']
    });
this.setValidators();
}
private setValidators() {
    let me = this;
    let status = true;
    me.morningForm.valueChanges.subscribe(fieldObj => {
      for (const fieldName in fieldObj) {
  // IF ENTER OR FIND THE VALUE THEN ALL FIELD SET AUTO REQUIRED VALIDATION.
        if (fieldObj[fieldName] != '') {
          status = true;
          break;
        }
      }
    });
    this.setRequiredField(status)
  }
  
  private setRequiredField(status:any) {
    let me = this;
    let country = me.morningForm.get('country');
    let city = me.morningForm.get('city');
    let phone = me.morningForm.get('phone');
    
    country.setValidators(null);
    city.setValidators(null);
    phone.setValidators(null);
    if (status) {
      country.setValidators([Validators.required]);
      city.setValidators([Validators.required]);
      phone.setValidators([Validators.required]);
    }
    country.updateValueAndValidity();
    city.updateValueAndValidity();
    phone.updateValueAndValidity();
  }
 

Share on Google Plus

About Ram Pukar

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment