表单控件设置值和更新有效性的方法

Method to set value and update validity of form control

我想知道是否有任何方法可以设置值和更新表单控件的有效性。鉴于以下内容:

this.updateForm = this._formBuilder.group({
    user: ['',Validators.required]     
});

我有一些具有更改触发器的指令,它会触发以下内容:

changeUserSelection(value){
    this.updateForm.controls['user'].value = value // doesnt trigger validation?
}

我想知道如何设置该值并触发该字段的验证。按我的方式执行此操作不会触发验证。

谢谢

您应该改用 updateValue 方法:

changeUserSelection(value){
  this.updateForm.controls['user'].updateValue(value);
}

更新到 Angular2 final

根据 angular2 的最终版本 updateValue 已更改为 setValue 所以新语法应该是这样的

changeUserSelection(value){
  this.updateForm.controls['user'].setValue(value);
}

您也可以试试 patchValue

this.updateForm.patchValue({ user: value });

对我来说setValuepatchValue不是自己做的。我为触发验证所做的操作如下:

form.controls[field].setValue(value);
form.controls[field].markAsTouched();
form.controls[field].markAsDirty();
form.controls[field].updateValueAndValidity();

这样我的验证消息就被正确触发了。我在没有 updateValueAndValidity 的情况下尝试过,但它没有用。

您可以尝试 this.form.updateValueAndValidity(); 更新多个控件的值和验证。