Reputation: 18699
I am wondering if there is any method to set value and update validity of a control of a form. Given the following:
this.updateForm = this._formBuilder.group({
user: ['',Validators.required]
});
I have some directive which has on change trigger, that triggers the following:
changeUserSelection(value){
this.updateForm.controls['user'].value = value // doesnt trigger validation?
}
And I am wondering how I can set the value, and trigger validation of this field. Doing this my way, doesnt trigger validation.
Thanks
Upvotes: 6
Views: 39244
Reputation: 119
You can try this.form.updateValueAndValidity();
to update value and validation for multiple controls.
Upvotes: 0
Reputation: 640
For me setValue
, patchValue
did not do the job by themselves. What I did to trigger the validation is the following:
form.controls[field].setValue(value);
form.controls[field].markAsTouched();
form.controls[field].markAsDirty();
form.controls[field].updateValueAndValidity();
That way my validation messages were triggered correctly. I tried without updateValueAndValidity
but it did not work.
Upvotes: 10
Reputation: 4421
You could also try patchValue
this.updateForm.patchValue({ user: value });
Upvotes: 4
Reputation: 86730
As per angular2's final release updateValue
has been changed to setValue
so the new syntax should be like this
changeUserSelection(value){
this.updateForm.controls['user'].setValue(value);
}
Upvotes: 9
Reputation: 202156
You should use the updateValue
method instead:
changeUserSelection(value){
this.updateForm.controls['user'].updateValue(value);
}
Upvotes: 4