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
We use the SetValue to update the FormControl , FormGroup or FormArray . When we use it to update the FormGroup or FormArray the SetValue requires that the object must match the structure of the FormGroup or FormArray exactly. Otherwise, it will result in an error.
Angular reactive forms follow a model-driven approach to handle form input whose values can be changed over time. These are also known as model-driven forms.
The FormGroup class exposes an API that enables us to set validators dynamically. We need to listen to optionB value changes and based on that we add or remove the validators we require. We also call the control's updateValueAndValidity() method, as we need to recalculate the value and validation status of the control.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With