当表单被禁用时,反应式表单有效 属性 return false
Reactive form valid property return false when form is disabled
我有这个简单的表单并用于创建和更新案例,因此对于创建案例,用户将输入数据并基于验证器我将得到 form.valid
(true,false)。
在更新案例中,我只是从 api 获取数据并将此值设置为表单并使表单禁用;
this.form = fb.group({
name: ['', Validators.required],
lastName: ['', Validators.required],
address: [''],
});
所以当我禁用表单时,有效值始终是 false
;
ngOnInit() {
this.form.patchValue({
name: 'name',
lastName: 'Last Name'
});
this.form.disable();
}
这是正确的。文档说:
A control is valid when its status is VALID.
状态文档说:
The validation status of the control. There are four possible validation status values:
- VALID: This control has passed all validation checks.
- INVALID: This control has failed at least one validation check.
- PENDING: This control is in the midst of conducting a validation check.
- DISABLED: This control is exempt from validation checks.
您的表单已被禁用,因此无效。
如果表单被禁用,Valid 将 return 为 false,所以我找到了两种解决方法
直接检查 valid
属性 我做了一个检查有效性的函数
isFormValid() : boolean {
return this.form.disabled ? true : this.form.valid
}
模板
<button [disabled]="!isFormValid()" (click)="update()">Update</button>
不创建 isFormValid 函数的另一种方式
<button [disabled]="!form.valid && form.disabled === false" (click)="update()">Update</button>
如果不是所有表单字段都被禁用,此时,在这种情况下使用反应式表单的最佳解决方法是将这些字段标记为只读。不完全相同,但这样你可以有一致的行为。
相关问题:
https://github.com/angular/angular/issues/11447
https://github.com/angular/material2/issues/15399
我有这个简单的表单并用于创建和更新案例,因此对于创建案例,用户将输入数据并基于验证器我将得到 form.valid
(true,false)。
在更新案例中,我只是从 api 获取数据并将此值设置为表单并使表单禁用;
this.form = fb.group({
name: ['', Validators.required],
lastName: ['', Validators.required],
address: [''],
});
所以当我禁用表单时,有效值始终是 false
;
ngOnInit() {
this.form.patchValue({
name: 'name',
lastName: 'Last Name'
});
this.form.disable();
}
这是正确的。文档说:
A control is valid when its status is VALID.
状态文档说:
The validation status of the control. There are four possible validation status values:
- VALID: This control has passed all validation checks.
- INVALID: This control has failed at least one validation check.
- PENDING: This control is in the midst of conducting a validation check.
- DISABLED: This control is exempt from validation checks.
您的表单已被禁用,因此无效。
如果表单被禁用,Valid 将 return 为 false,所以我找到了两种解决方法
直接检查 valid
属性 我做了一个检查有效性的函数
isFormValid() : boolean {
return this.form.disabled ? true : this.form.valid
}
模板
<button [disabled]="!isFormValid()" (click)="update()">Update</button>
不创建 isFormValid 函数的另一种方式
<button [disabled]="!form.valid && form.disabled === false" (click)="update()">Update</button>
如果不是所有表单字段都被禁用,此时,在这种情况下使用反应式表单的最佳解决方法是将这些字段标记为只读。不完全相同,但这样你可以有一致的行为。
相关问题:
https://github.com/angular/angular/issues/11447 https://github.com/angular/material2/issues/15399