我有一个包含 2 个字段的表单:
- includeValidation,一个选择下拉菜单(2 个选项):有验证,没有验证
- 金额,输入数字字段
根据第一个下拉列表,我在第二个字段上有验证器:Validators.required,Validators.min(0.1)。
我试图使用 clearValidators() 来删除验证,但它只删除了所需的而不是 min(0.1)
当includeValidation ==“没有验证”时如何删除min(0.1)
表单测试.ts
ngOnInit(): void {
this.initForm();
this.initValueChanges();
}
initForm(): void {
this.addForm = this.formBuilder.group({
includeValidation: [''],
amount: [0, [Validators.required, Validators.min(0.1)]]
});
}
initValueChanges() {
this.addForm.get('includeValidation').valueChanges.subscribe((value) => {
if(value === 'with validation') {
this.addForm.get('amount').setValidators([Validators.required, Validators.min(0.1)]);
} else if(value === 'without validation') {
this.addForm.get('amount').setValue(0);
this.addForm.get('amount').clearValidators();
}
});
}
previewSaveButton() {
this.addForm.get('amount').updateValueAndValidity();
if(this.addForm.valid) {
}
}
表单测试.html
<form novalidate role="form" name="addForm" [formGroup]="addForm">
<div class="row">
<div class="col-md-12">
<h5>General</h5>
<div class="form-group"><label>include Validation</label>
<select name="includeValidation" class="form-control" formControlName="includeValidation">
<option></option>
<option value="with validation">with validation</option>
<option value="without validation">without validation</option>
</select>
</div>
<div class="form-group"><label>amount</label>
<input name="amount" type="text" class="form-control" formControlName="amount">
</div>
</div>
</div>
<hr />
<div>
<div class="d-flex justify-content-end">
<button type="submit" (click)="previewSaveButton()">Next</button>
</div>
</div>
</form>