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



我想知道是否有任何方法可以设置值并更新表单控件的有效性

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

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

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

我想知道如何设置该值,并触发该字段的验证。按照我的方式这样做,不会触发验证。

感谢

更新到Angular2 final

根据angular 2的最终版本,updateValue已更改为setValue所以新的语法应该像这个

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

对我来说,setValuepatchValue并不是自己完成这项工作的。我触发验证的方法如下:

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

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

您应该使用updateValue方法:

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

您也可以尝试patchValue

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

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

最新更新