Search code examples
angularangular2-forms

Add/remove reactive form validators to dynamically created inputs


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?


Solution

  • 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()