Angular 13:尝试为 FormGroup 创建自定义验证器时'AbstractControl.parent is possibly null'



我有一个包含一组复选框的表单,我想创建一个自定义验证器,强制检查其中至少一个。

form.component.ts


form: FormGroup = new FormGroup({
customer: new FormControl('', [Validators.required]),
partTimeidentification: new FormControl('', [Validators.required]),
inspectionType: new FormGroup({
ocr: new FormControl(false, []),
anomalyDetection: new FormControl(false, []),
metrics: new FormControl(false, []),
wiresInspection: new FormControl(false, []),
other: new FormControl(false, []),
}, { validators: atLeastOneValidator() }),
cameraSettings: new FormGroup({
model: new FormControl('', [Validators.required]),
size: new FormControl('', [Validators.required]),
speedOb: new FormControl('', [Validators.required]),
flashColor: new FormControl('', [Validators.required]),
}),
});

form.component.html(我省略了字段以使其尽可能清晰,这里有结构):

<form class="flex-col text-center" [formGroup]="form!">
(more fields here)
<app-box [title]="'Inspection type'" class="text-center me-2" [fit_height]="true" formGroupName="inspectionType">
<div class="form-check">
<input class="form-check-input" type="checkbox" formControlName="ocr" name="ocr" value="ocr"/>
<label class="form-check-label"> OCR </label>
</div>
(more checkboxes)
</app-box>
(more fields)
<button [disabled]="!form!.valid" type="button" class="btn bg-primary-tb text-white mt-3 col-4" (click)="submit()">Continue </button>
</form>

atLeastOneValidator.directive.ts

import { AbstractControl, ValidationErrors, ValidatorFn } from "@angular/forms";
export function atLeastOneValidator(): ValidatorFn {
return (group: AbstractControl): ValidationErrors | null => {
let controls = group.parent.controls;
let theOne = Object.keys(controls).findIndex(key => controls[key].value !== false);

if (theOne) return null;

return { 'atLeastOneRequired': 'At least one should be selected'}
};

};

尽管如此,我还是不断收到error TS2531: Object is possibly 'null'.验证器group.parent中的错误消息。

将验证器的代码用文字表达:我想访问父级(我猜它是inspectionType,一个FormGroup),然后查看是否有任何子级(ocranomalyDetection......这些FormControls)中的任何一个都设置为 true,在这种情况下,表单有效。

创建一个需要FormGroup的验证器,然后将验证器附加到FormGroup,该是FormControl的父级,其中至少有一个必须为真。

// validator
function atLeastOneValidator() {
return (control: FormGroup) => {
const raw = control.getRawValue();
return Object.keys(raw).map(k => raw[k]).some(_ => _) ? null : {check_one: "Must check at least one"}
}
}
// form group
fg: FormGroup;
constructor(private fb: FormBuilder) {
this.fg = this.fb.group({
a: this.fb.control(false),
b: this.fb.control(false),
c: this.fb.control(false),
}, {validators: [atLeastOneValidator()]});
}

最小堆栈闪电战:https://stackblitz.com/edit/angular-ivy-f3c3e1?file=src/app/app.component.ts

相关内容

最新更新