最近,在用angular写一个考试的功能,就是循环后台数据,主要是题目和答案,这对有基础的童鞋来说,so easy。项目UI框架选的是NG-ZORRO,但是做的时候发现一个问题,form组件的验证不会对复选框组起作用,也就是提交的时候不会提示你没有答这道多选题,这就很麻烦。
后来找到了一种投机取巧的方法,但是使用的时候会报警告,这就看看你是不是有强迫症非得要log干干净净了,当然如果你想自定义验证肯定也是可以的,也不会有warning。
话不多说,直接上代码吧!
html:
<form nz-form [formGroup]="validateForm" (ngSubmit)="submitForm()">
<nz-form-item class="mar_bot_10">
<nz-form-label [nzSpan]="2" class="form-label" nzRequired nzFor="userName">姓名</nz-form-label>
<nz-form-control [nzSpan]="7" nzErrorTip="请填写姓名">
<input formControlName="userName" nz-input placeholder="请输入姓名" [disabled]="disabled"/>
</nz-form-control>
</nz-form-item>
<button *ngIf="!score" nz-button class="form-button" [nzType]="'primary'">提交</button>
<nz-form-item *ngFor="let data of dataMap[0]?.questions;let num = index;">
<nz-form-label [nzSpan]="24" class="form-label" nzRequired nzFor="one">{{data?.question}}</nz-form-label>
<nz-form-control nzErrorTip="请答此题!">
<nz-radio-group [formControlName]="'field'+num" [nzDisabled]="disabled" *ngIf="data.type === 'single'">
<label nz-radio [nzValue]="value.key" *ngFor="let value of data?.options">{{value.key}}.{{value.value}}</label>
</nz-radio-group>
<nz-radio-group [formControlName]="'field'+num" [nzDisabled]="disabled" *ngIf="data.type === 'judge'">
<label nz-radio [nzValue]="value.key" *ngFor="let value of data?.options">{{value.key}}.{{value.value}}</label>
</nz-radio-group>
<nz-checkbox-wrapper style="width: 100%;" (nzOnChange)="log($event,'field'+num)" *ngIf="data.type === 'multi'">
<div nz-row>
<div nz-col nzSpan="16" *ngFor="let value of data?.options"><label [formControlName]="'field'+num" [nzDisabled]="disabled" nz-checkbox [nzValue]="value.key">{{value.key}}.{{value.value}}</label></div>
</div>
</nz-checkbox-wrapper>
</nz-form-control>
<nz-form-label [nzSpan]="24" class="form-label" nzRequired nzFor="one" *ngIf="disabled">正确答案:{{data?.answer}}</nz-form-label>
</nz-form-item>
</form>
ts:
log(value: string[], key: string | number): void {
this.checkBox[key] = value.join(',');
}
submitForm(): void {
if (this.validateForm.valid) {
const array = {...this.validateForm.value, ...this.checkBox};
} else {
Object.values(this.validateForm.controls).forEach(control => {
if (control.invalid) {
control.markAsDirty();
control.updateValueAndValidity({ onlySelf: true });
}
});
}
}
其实,中心思想就是提交的时候把获取的多选值赋予给验证的值,因为验证时验证的是单独的checkbox,然后正常提交就可以了。
希望能对看到的人有点用吧~代码没有全部粘出来,有问题请留言吧!
全文完~