I am using FormArray and Reactive Forms Module to dynamically generate checkboxes.
My requirement is to disable the remaining checkboxes once the user selects any 2 checkboxes. If the user deselects one, they should be able to select from the others again. When 2 selections are made, all other checkboxes should be disabled.
Here is the HTML code:
<form [formGroup]="userForm" (ngSubmit)="onFormSubmit()">
<label>
<b>Time Out Period :</b>
</label>
<div class="input-group">
<input type="text" class="form-control" maxlength="2" formControlName="tbl_config_TimeoutPeriod">
</div>
<div *ngIf="tbl_config_TimeoutPeriod.invalid && tbl_config_TimeoutPeriod.touched">
<span style="color:red;margin-top:3px">Time Out Period field is mandatory..!</span>
</div>
<br>
<div formArrayName="users">
<div *ngFor="let user of users.controls; index as idx">
<input [formControlName]="idx" type="checkbox" >
<button (click)="deleteUserField(idx)">Delete</button>
</div>
</div>
<br>
<button type="submit" [disabled]="!userForm.valid" class="btn btn-primary">Save Changes</button>
<button type="button" (click)="addUserField()">Add More User</button>
</form>
Following is the TypeScript code:
userForm = new FormGroup({
tbl_config_TimeoutPeriod: new FormControl('', Validators.required),
users: new FormArray([
new FormControl('', Validators.required)
])
});
get users(): FormArray { return this.userForm.get('users') as FormArray; }
get tbl_config_TimeoutPeriod() { return this.userForm.get('tbl_config_TimeoutPeriod'); }
onFormSubmit() {
console.log(this.userForm.value); // Provides complete form data
}
addUserField() {
this.users.push(new FormControl(''));
}
deleteUserField(index: number) {
this.users.removeAt(index);
}