如果未选中我的表单组中的复选框,则需要显示验证错误消息。不能使用jquery,所有操作都必须使用angular 7完成。这是一种反应形式。 我尝试设置ngIf条件,并应用条件验证功能,但没有一个起作用。 这是我的表单组中包含复选框的一部分
initForm() {
this.financialSectionSix = this.formBuilder.group({
medicaidOrSssi: [false],
snap: [false],
freeOrReducedPriceLunch: [false],
tanf: [false],
wic: [false],
noneOfTheAbove: [false]
});
}
这是HTML的一部分
<div [hidden]="selectedSectionGroup.sectionSix" class="tab-pane fade show active"
id="{{financialSectionEnum.SECTION_SIX}}" role="tabpanel">
<form [formGroup]="financialSectionSix">
<label class="form-check-label" for="financial1">
<input required formControlName="medicaidOrSssi" id="medicaidOrSssi" class="form-check-input"
data-hint="yes" type="checkbox" value="true">
Medicaid or Supplemental Security Income (SSI)
</label>
<label class="form-check-label" for="cada-form-student-financial-section-6-1-2">
<input required formControlName="snap" id="snap" class="form-check-input" data-hint="yes" type="checkbox"
value='true'>
Food Stamps or Supplemental Nutrition Assistance Program (SNAP)
</label>
</form>
</div>
选中其中一个框时,该值应从false更改为true,如果未选中,则应将值从true更改为false。
答案 0 :(得分:0)
我想您需要为此定制一个验证器,例如:
selectAtleastOne(c: FormGroup) {
const selectAtleastOne = Object.values(c.value).some(Boolean);
return selectAtleastOne ? null : {
selectAtleastOne: {
valid: false,
error: true
}
};
}
您可以像这样使用它:
this.financialSectionSix = this.formBuilder.group({
medicaidOrSssi: [false],
snap: [false],
freeOrReducedPriceLunch: [false],
tanf: [false],
wic: [false],
noneOfTheAbove: [false]
}, { validator: this.selectAtleastOne });
在HTML中:
<form [formGroup]="financialSectionSix">
<label class="form-check-label" for="financial1">
<input required formControlName="medicaidOrSssi" id="medicaidOrSssi" class="form-check-input"
data-hint="yes" type="checkbox" value="true">
Medicaid or Supplemental Security Income (SSI)
</label><br>
<label class="form-check-label" for="cada-form-student-financial-section-6-1-2">
<input required formControlName="snap" id="snap" class="form-check-input" data-hint="yes" type="checkbox"
value='true'>
Food Stamps or Supplemental Nutrition Assistance Program (SNAP)
</label>
<div style="color: red" *ngIf="financialSectionSix?.errors?.selectAtleastOne?.error">Select atleaset one</div>
<br>
<div>{{financialSectionSix.value | json}}</div>
</form>