gpt4 book ai didi

forms - Angular 2 - FormControl setValue 'onlySelf' 参数

转载 作者:太空狗 更新时间:2023-10-29 16:54:15 26 4
gpt4 key购买 nike

试图了解传递给 setValue 时“onlySelf”参数的作用。

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

文档说:“如果 onlySelf 为 true,则此更改只会影响此 FormControl 的验证,而不影响其父组件。默认为 false。”

但是我很难理解这一点。对使用 Angulars 的模型驱动表单还是相当陌生。

最佳答案

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.validtrue

如果您使用默认设置 (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

关于forms - Angular 2 - FormControl setValue 'onlySelf' 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39602837/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com