Angular / Form / Dynamic Validation
Dynamic Validation based on select box option
-
Steps
1. in view
Please select a statusPlease select a agent2. in component
... .. this.statusForm = this.fb.group({ 'status_id': ['', Validators.required], 'agent_id' :[''], }); .... ..... onchangeSelect(event, fieldName){ if(fieldName=='status_id'){ let stage= this.formOptionData['status_id'].find( fella => fella.id == event.target.value) console.log(stage); this.showAgentPanel=false; this.statusForm.controls['agent_id'].clearValidators(); if(stage.identifier=='sent_to_agent'){ this.showAgentPanel=true; this.statusForm.controls['agent_id'].setValidators([Validators.required]); } this.statusForm.get('agent_id').updateValueAndValidity(); } } loadOptionData(url, type, value){ this.commonService.options(url) .subscribe(response => { //console.log(response.length); this.formOptionData[type]=response; if(response.length==1){ this.mainForm.get(type).patchValue(response[0].id); } document.getElementById("overlay").style.display = "none" }); }