Angular 2 - FormControl parameter setValue 'onlySelf'

Trying to understand what the onlySelf parameter does when passing to setValue.

this.form.get('name').setValue('', { onlySelf: true }) 

The documentation says: "If onlySelf is true, this change will only affect the validation of this FormControl, and not its parent component. By default, this value is false.

However, I am struggling to figure this out. Still quite new to using Angulars managed forms.

+8
angular forms setvalue
source share
2 answers

Angular2, by default, checks that the control form / group form is cascaded to the top level when there is an update to the value of the form element, unless you say no. onlySelf is a tool to help you with this.

Say you have a loginForm that has a username field and a password field, both of which are necessary, for example:

 this.userNameControl = this.formBuilder.control('Harry', Validators.required); this.passwordControl = this.formBuilder.control('S3cReT', Validators.required); this.loginForm = this.formBuilder.group({ userName: this.userNameControl, password: this.passwordControl }); 

After this code, this.loginForm.valid is true .

If you set the control value using the default value ( onlySelf = false ), Angular2 will update the correctness of the action, as well as the validity of the form group. For example, this:

 this.passwordControl.setValue(''); 

will result in

 this.passwordControl.valid === false this.loginForm.valid === false 

However, this:

 this.passwordControl.setValue('', { onlySelf: true }); 

only changes the validity of passwordControl :

 this.passwordControl.valid === false this.loginForm.valid === true 
+13
source share

Put it this way, let's say you have a form called mainForm that is valid . There are four controls on it, and all four matter. Now you decide to update the value of one of your controls, for example, you updated it to some incorrect value and specified onlySelf: true . If you try to call this.mainForm.valid , you will get a result in which your form is valid , even if your control is not valid , and this invalid state should not allow the form to be submitted. But since the valid valid property reports true, you will present conflicting values ​​for the backend.

You may be confused why you have this property, but there may be times when you do not want to cancel the form due to a single value or control. You probably have some advanced checks on the server, and you want to fix this value on the server, or you can depend on the value from some external web service that might not be available at that time. I am sure there are several scenarios, but this is something from the top of the head.

+2
source share

All Articles