【发布时间】:2017-09-20 11:50:20
【问题描述】:
有什么方法可以在声明后更新控件,比如
this.input = new FormControl('', Validators.required)
this.form = this.formBuilder.group({
input = this.input
})
this.input.update('', Validators.maxlength(20))
【问题讨论】:
有什么方法可以在声明后更新控件,比如
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();
如果你想更新字段值,你可以使用patchValue。
【讨论】: