20
votes

I have created a form in Angular 4, which allows the user to click an ADD or REMOVE button in the form to add/remove fields to the form. I use ngFor to create the html inputs on screen from an array (enlarged by the add function, or shrunk by the remove function).

In the html template I can add formControlName in the form formControlName="control{{index}}" to ensure each new input has a formcontrol.

But how do I dynamically add and remove validators for these inputs?

2
Possibly similar to this? ► stackoverflow.com/questions/41175411/…Nope

2 Answers

52
votes

can you look at this document https://angular.io/api/forms/AbstractControl#updateValueAndValidity,

for add/remove controls you can use these methods

addControl/removeControl

for value and validators you can use like this

 this.form.controls['test_control'].setValidators([Validators.required])
 this.form.controls['test_control'].updateValueAndValidity()
0
votes

Source Link

For Angular 11 Use setValidators() and updateValueAndValidity() methods

  setRequired() {
    this.profileForm.controls.firstName.setValidators([Validators.required]);
    this.profileForm.controls.firstName.updateValueAndValidity();
  }

  unsetRequired() {
    this.profileForm.controls.firstName.setValidators(null);
    this.profileForm.controls.firstName.updateValueAndValidity();
  }