更新 FormControl 中的验证器

Update Validators in FormControl

有没有办法在声明后更新控件,比如

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

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

您可以使用 setValue 方法或 patchValue 方法更新 FormControl 或 FormGroup。在您的情况下,最好使用 setValue

patchValue 的作用是,如果您想用某个对象更新表单,并且该对象包含的属性比表单多(这意味着表单上不存在某些属性),则使用 patchValue 它将只获取存在于表单上的值,在这种情况下如果使用 setValue,将会出错。对于更多类似的问题,最好使用文档(比我在这里解释的更详细)

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

如果您想稍后设置新的验证器,您可以使用 setValidators,您可能还想更新值和有效性,它可以是 运行 updateValueAndValidity。这是一个简单的例子:

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

this.myForm.get('input').updateValueAndValidity();

Demo

如果你想更新字段值,你可以使用 patchValue.