Search code examples
angularangular2-forms

Update Validators in FormControl


is there any way to update control after it declared, like

this.input = new FormControl('', Validators.required)
this.form = this.formBuilder.group({
  input = this.input
})

this.input.update('', Validators.maxlength(20))

Solution

  • You can use setValidators if you want to set new Validator(s) at a later point, you'd probably also want to update the value and validity, it can be run with updateValueAndValidity. Here's a simple example:

    this.myForm.get('input').setValidators([Validators.required, 
                                              Validators.minLength(4)]);
    
    this.myForm.get('input').updateValueAndValidity();
    

    Demo

    And if you want to update the field value, you can as mentioned use patchValue.