Update Validators in FormControl

2019-05-21 03:46发布

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

2条回答
淡お忘
2楼-- · 2019-05-21 04:06

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

查看更多
做个烂人
3楼-- · 2019-05-21 04:16

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.controls.input.setValidators([Validators.required, 
                                          Validators.minLength(4)]);

this.myForm.controls.input.updateValueAndValidity();

Demo

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

查看更多
登录 后发表回答