Angular中FormControl有效性测试异常:设置值后验证未生效
Angular FormControl 有效性测试问题解决
问题原因
你当前的FormControl仅配置了Validators.required验证器,仅检查值是否为空。HTML中的[min]="1.0"是原生input的属性,不会同步到Angular表单的验证逻辑中,所以设置值为0时,因为值不为空,valid状态始终为true。
修改步骤
1. 更新FormControl的验证器
在组件TS文件中,为budget添加Validators.min(1)验证器,确保输入值大于等于1:
import { Validators, FormControl } from '@angular/forms'; // ... budget = new FormControl(null, [Validators.required, Validators.min(1)]);
2. 清理HTML中的冲突属性
同时使用[ngModel]和[formControl]会导致表单状态混乱,建议移除[ngModel]和value属性,由FormControl单独管理输入值:
<input id="budget" currencyMask placeholder="Dollar" [formControl]="budget" [options]="{decimal: ',', thousands: '.', allowNegative: false }" type="text" />
如果需要从modelService.budget初始化值,在组件初始化时通过FormControl的setValue方法设置:
ngOnInit() { this.budget.setValue(this.modelService.budget); }
3. 调整测试用例
完善测试逻辑,确保验证器正确生效:
it('should be invalid when value is 0', fakeAsync(() => { component.ngOnInit(); component.budget.setValue(0); fixture.detectChanges(); // 模拟用户触发表单控件 component.budget.markAsTouched(); fixture.detectChanges(); expect(component.budget.valid).toBe(false); })); it('should be valid when value is 10', fakeAsync(() => { component.ngOnInit(); component.budget.setValue(10); fixture.detectChanges(); component.budget.markAsTouched(); fixture.detectChanges(); expect(component.budget.valid).toBe(true); }));
内容的提问来源于stack exchange,提问作者sebi.schneider
相关产品推荐
相关产品推荐

