Home > Net >  Angular Material Checkbox disabled on condition
Angular Material Checkbox disabled on condition

Time:12-01

In my Angular application I have a dynamically generated reactive form with multiple FormArrays. On of these FormArrays contains 6 checkboxes. I only want a user to be able to check 3 boxes, so I have a count for the amount of selected checkboxes. When the count is over 3 a boolean is set to true and if the count is under 3 it is set to false again. The problem here is that once the checkboxes are disabled, a user can not unselect one of his selected boxes since the checkboxes are completely disabled.

What i am trying to accomplish is that unselected checkboxes can no longer be selected once the count is higher than 3, while the user is still able to unselect his already selected checkboxes.

I am using the Angular Material checkboxes with the [disabled] attribute. How can I achieve described behaviour?

HTML

<mat-checkbox *ngIf="option.key === 'vacancy'" (change)="onCheckboxChangeEvent(option.key, value, $event)" [checked]="isActiveValue(optie.key, value)" [disabled]="vacancyDisabled">
                            {{ value }}</mat-checkbox>

TS

onCheckboxChangeEvent(
    key: string,
    value: string,
    event: MatCheckboxChange
): void {
    const feature = this.candidateForm?.get(key) as FormArray;

    if (event.checked) {
        if (key === 'vacancy') {
            this.selectedVacancy  ;
            if (this.selectedVacancy >= 3) {
                this.vacancyDisabled = true;
                console.log('disable');
            }
        }
        feature.push(new FormControl(value));
    } else {
        if (key === 'vacancy') {
            this.selectedVacancy--;
            if (this.selectedVacancy <= 3) {
                this.vacancyDisabled = false;
                console.log('enable');
            }
        }
        const index = feature.controls.findIndex((x) => x.value === value);
        feature.removeAt(index);
    }
}

CodePudding user response:

You can use checked value to disable only unchecked checkboxes

<mat-checkbox *ngIf="option.key === 'vacancy'" (change)="onCheckboxChangeEvent(option.key, value, $event)" 
[checked]="isActiveValue(optie.key, value)" 
[disabled]="vacancyDisabled  && ! isActiveValue(optie.key, value)">
{{ value }}
</mat-checkbox>
  • Related