I'm working on a form with Angular Forms and I have hit a deadend where I want to add validation to a second input field only if the first is not empty.
Let's say I have two input fields: name and age. So when something is typed into name, only then age will be set to required. I'm using FormGroup and FormControl for my form and this is how the component file looks like now without validators for age:
class Component implements OnChanges {
@Input() name: string;
@Input() age: string;
form = new FormGroup({
name: new FormControl(''),
age: new FormControl('')
});
ngOnChanges(changes) {
if (changes.name?.currentValue !== changes.name?.previousValue) {
this.setName(changes.name.currentValue);
}
if (changes.age?.currentValue !== changes.age?.previousValue) {
this.setAge(changes.age.currentValue);
}
}
setName(name) {
this.form.patchValue({
name,
});
if (name) {
this.form.get('age').setValidators([
Validators.required,
this.form.get('age').validator
]);
}
}
setAge(age) {
this.form.patchValue({
age,
});
}
}
Here's the template:
<custom-input
label="Name"
placeholder="name"
name="name"
formControlName="name"
></custom-input>
<custom-input
label="Age"
placeholder="age"
name="age"
formControlName="age"
></custom-input>
*ngIfcondition to your second input field.