Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to set value and update validity of form control

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

like image 466
uksz Avatar asked Mar 31 '16 13:03

uksz


People also ask

Which method is used to update the form values?

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.

Which method is used to update the form values in Angular?

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.

Which method is used to add dynamic validation to the 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.


2 Answers

Update to Angular2 final

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);
}
like image 119
Pardeep Jain Avatar answered Oct 24 '22 20:10

Pardeep Jain


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.

like image 24
Vallerious Avatar answered Oct 24 '22 19:10

Vallerious