Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 449
TSG Avatar asked Sep 06 '17 15:09

TSG


People also ask

How do I remove a validator from a form dynamically?

1. setValidators() method removes all the previous/default validators from form control. For example, let's suppose during form initialization, you set maxLength and minLength validators for County . But once setValidators([Validators.

How do I add custom validators dynamically in reactive form?

We can add Validators dynamically using the SetValidators or SetAsyncValidators. This method is available to FormControl, FormGroup & FormArray. There are many use cases where it is required to add/remove validators dynamically to a FormControl or FormGroup.

How do you add validators in reactive form?

Adding async validators to reactive formslink To use an async validator in reactive forms, begin by injecting the validator into the constructor of the component class. Then, pass the validator function directly to the FormControl to apply it.

Which method is used to add dynamic validation to the forms in angular?

Dynamically Add Validators We need to listen to optionB value changes and based on that we add or remove the validators we require. We also call the control's updateValueAndValidity() method, as we need to recalculate the value and validation status of the control.


3 Answers

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()
like image 52
Robert Avatar answered Oct 04 '22 12:10

Robert


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();
  }
like image 26
Code Spy Avatar answered Oct 04 '22 14:10

Code Spy


Angular 13. It's working for me...

OnInit Func:

ngOnInit() {
    this.form.get('type')?.valueChanges.subscribe((val) => {
      if (val) {
        switch (val) {
          case 1:
            this.removeValidators(['comment', 'id']);
            this.addValidators(['desc', 'options']);
            break;
          case 2:
            this.removeValidators(['desc', 'options', 'comment']);
            this.addValidators(['id']);
            break;
        }
      }
    });
}

Func (Add/Remove Validators):

addValidators(controls : string[]){
    controls.forEach(c => {
        if(['desc','comment'].includes(c)){
            this.form.get(c)?.setValidators([Validators.required,Validators.maxLength(250)]);
        } else {
            this.form.get(c)?.setValidators(Validators.required);
        }
        this.form.get(c)?.updateValueAndValidity();
    });
}

removeValidators(controls : string[]){
    controls.forEach(c => {
        this.form.get(c)?.clearValidators();
        this.form.get(c)?.updateValueAndValidity();
    });
}
like image 27
sweetnandha cse Avatar answered Oct 04 '22 14:10

sweetnandha cse