Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 529
Jarosław Rewers Avatar asked Apr 23 '17 22:04

Jarosław Rewers


2 Answers

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.

like image 160
AT82 Avatar answered Sep 25 '22 22:09

AT82


You can update a FormControl or FormGroup with the setValue method, or the patchValue method. In your case it is better to use setValue.

What patchValue does is if you want to update your form with some object, and that object contains more properties than the form (which means some properties do not exist on the form), with patchValue it will only get the values which exist on the form, and in this case if you use setValue, there will be an error. For more questions like this, its always best if you use the documentation (which has way more details than what I can explain here)

https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html

like image 39
Denko Mancheski Avatar answered Sep 25 '22 22:09

Denko Mancheski