默认情况下,只要任何表单元素值有更新,除非您拒绝,否则 Angular2 将逐级检查表单控件/表单组的有效性,直至顶层。 onlySelf 是帮助您做到这一点的工具。
假设您有一个loginForm,其中包含一个username 字段和一个password 字段,这两个字段都是必需的,如下所示:
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
});
在这段代码之后,this.loginForm.valid 是true。
如果您使用默认设置 (onlySelf = false) 设置控件的值,Angular2 将更新控件的有效性以及表单组的有效性。例如,这个:
this.passwordControl.setValue('');
将导致
this.passwordControl.valid === false
this.loginForm.valid === false
但是,这个:
this.passwordControl.setValue('', { onlySelf: true });
只会改变passwordControl的有效性:
this.passwordControl.valid === false
this.loginForm.valid === true