I have a reactive form which contain a list of checkboxes and if one of them is checked an input form will be displayed. How can I add a validator to ensure that at least one checkbox should be selected.
This is my component.ts :
coveragestypes : Array<ItemPolicyModel>=
[{id:'1', name :'type 1'},
{id : '2',name :'type 2'},
{id : '3',name :'type 3'},
{id:'4',name:'type 4'}]
coveragesObject : any = null;
policyForm = new FormGroup({
coveragesObject : new FormArray([])
})
ngOnInit() {
this.addCheckboxes();
}
addCheckboxes() {
let formGroups: FormGroup[] = this.coveragestypes.map(coverage => {
return new FormGroup({
id: new FormControl(coverage.id),
name: new FormControl(coverage.name),
value: new FormControl("", Validators.pattern(/^-?(0|[1-9]\d*)?$/)),
checked: new FormControl(false)
});
});
this.coveragesObject = new FormArray(formGroups);
this.policyForm.setControl('coveragesObject', this.coveragesObject );
}
And this is my component.html :
<div *ngFor="let coverage of coveragesObject.controls;let i = index; ">
<div [formGroup]="coverage">
<input type="checkbox" kendoCheckBox [formControl]="coverage.controls.checked" />
{{coverage.controls.name.value}}
<ng-container *ngIf="coverage.controls.checked.value">
<input type="text" [formControl]="coverage.controls.value" style=" height: 100%;max-height:10px;padding : 0.5rem 0.75rem;
border-color: rgba(0, 0, 0, 0.125);width: 40%;">
<span style="position: absolute;padding : 0.05rem 0.25rem ;">£</span>
<div *ngIf="coverage.controls.value.invalid"
style="font-size: xx-small; color : red">
{{ "newRepair.intake.policyInfo.ownrisk" | translate }}
</div>
</ng-container>
</div>
</div>
Can anyone help me, please?