Reputation: 687
I'm currently dynamically generating a form input using *ngIf and if this form input us in the DOM it is a required input however if it is not it should not be required.
How can I achieve this using the reactive forms approach?
HTML
<select formControlName="input" name="input">
<option value="1">1</option>
<option value="2">2</option>
</select>
<div *ngIf="input === '2'">
<textarea formControlName="inputDynamic" name="inputDynamic" type="text"></textarea>
</div>
COMPONENT
initApplicants() {
return this.fb.group({
input: ['', Validators.required],
inputDynamic: ['', Validators.required]
});
}
Let me know if you require any further details.
Upvotes: 0
Views: 315
Reputation: 1240
If you want to keep to the reactive approach you may want to add and remove validators when your app runs. Subscribe to changes first:
this.formName.controls['input'].valueChanges().subscribe(value => {
if (value === 2) {
//remove validators
} else {
//add validators
}
});
this.formName.controls['controlName'].setValidators(null)
will remove validators.
this.formName.controls['controlName'].setValidators(Validators.required)
will add validator.
don't forget to call this.formName.controls['controlName'].updateValueAndValidity()
after you do these operations.
Upvotes: 1
Reputation: 7231
Using *ngIf
input will be loaded/removed again so the better way to use validations with template.
Set required in element like this:
<div *ngIf="input === '2'">
<textarea required formControlName="inputDynamic" name="inputDynamic" type="text"></textarea>
</div>
and remove from component:
initApplicants() {
return this.fb.group({
input: ['', Validators.required],
inputDynamic: ['', Validators.required] <===== Remove required from here (used in template)
});
}
Upvotes: 0