Angular 2-FormControl setValue'onlySelf'参数 [英] Angular 2 - FormControl setValue 'onlySelf' parameter

查看:337
本文介绍了Angular 2-FormControl setValue'onlySelf'参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图了解传递给setValue时'onlySelf'参数的作用.

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

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

文档说:如果onlySelf为true,则此更改将仅影响此FormControl的验证,而不影响其父组件.默认值为false."

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

但是我正在努力理解这一点.对于使用Angulars模型驱动的表单来说还是相当新的东西.

However I'm struggling to understand this. Still fairly new to the using Angulars' model driven forms.

推荐答案

默认情况下,Angular2会在对任何表单元素值进行更新时,逐级检查表单控件/表单组的有效性,直到最高级别为止,除非您说不. . onlySelf是帮助您完成此任务的工具.

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.

假设您有一个loginForm,其中有一个username字段和一个password字段,这两个字段都是必需的,如下所示:

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

此代码后,this.loginForm.validtrue.

如果使用默认设置(onlySelf = false)设置控件的值,Angular2将更新控件的有效性以及表单组的有效性.例如,这:

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('');

将导致

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

但是,这:

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

仅会更改passwordControl的有效性:

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

这篇关于Angular 2-FormControl setValue'onlySelf'参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆