Angular 2 - FormControl setValue 'onlySelf' parameter

后端 未结 2 1736
天涯浪人
天涯浪人 2020-12-29 03:58

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

this.form.get(\'name\').setValue(\'\', { onlySelf: true })
2条回答
  •  臣服心动
    2020-12-29 04:45

    Angular2 by default will check for the form control/form group validity cascadingly up to the top level whenever there's an update to any form element value, unless you say no. onlySelf is the tool to help you do that.

    Say you have a loginForm that has a username field and a password field, both of them are required, like this:

    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 value of a control using the default setting (onlySelf = false), Angular2 will update the control's validity as well as form group's validity. For example, this:

    this.passwordControl.setValue('');
    

    will result in

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

    However, this:

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

    will only change passwordControl's validity only:

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

提交回复
热议问题