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))
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With