【问题标题】:Update Validators in FormControl在 FormControl 中更新验证器
【发布时间】: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))

【问题讨论】:

    标签: angular angular2-forms


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

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

      Demo

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

      【讨论】:

        猜你喜欢
        • 2017-02-15
        • 2018-07-10
        • 2017-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-25
        • 2023-03-27
        • 1970-01-01
        相关资源
        最近更新 更多