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();
}
0 comments:
Post a Comment