uksz
uksz

Reputation: 18699

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

Upvotes: 6

Views: 39244

Answers (5)

You can try this.form.updateValueAndValidity(); to update value and validation for multiple controls.

Upvotes: 0

Vallerious
Vallerious

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

Mackelito
Mackelito

Reputation: 4421

You could also try patchValue

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

Upvotes: 4

Pardeep Jain
Pardeep Jain

Reputation: 86730

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);
}

Upvotes: 9

Thierry Templier
Thierry Templier

Reputation: 202156

You should use the updateValue method instead:

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

Upvotes: 4

Related Questions