How to properly handle mutually exclusive checkbox selection with reactive forms

Discussão em 'Angular' iniciado por Sunny, Março 17, 2025.

  1. Sunny

    Sunny Guest

    I need some assistance with handling checkbox selection using angular. I have 4 checkboxes, ALL, FirstName, LastName, MiddleName. When the page loads ALL should be the only one selected. If I click any of the other boxes ALL should be deselected. Likewise if I click ALL again the other checkboxes should be deselected. Currently ALL is selected when the page loads. I then can click the other boxes. However I can't click ALL unless I manually uncheck the other boxes. Any assistance you can provide will be greatly appreciated.

    I am using component projection to include the child form type filter in the parent.html.

    — parent html

    <form [formGroup]="reportListFG">
    <app-form-type-filter
    [formGroup] ="reportListFG.get('filterGroup')"
    (formTypeFilterChanged)="onFormTypeSelectionChange($event)"
    (clear)="clearReceipt($event)"
    #formFilter></app-form-type-filter>


    —parent ts

    this.reportListFG = this.fb.group(
    {
    Address: [[]],
    PhoneNumber: [[]],
    filterGroup: this.fb.group({
    ALL: [true],
    FirstName: [false],
    LastName: [false],
    MiddleName: [false],
    }),


    )
    // Listen to form changes and handle the logic for "All" and other checkboxes
    this.reportListFG.get('filterGroup').valueChanges.subscribe(values => {
    this.handleCheckboxSelection(values);
    });

    }

    handleCheckboxSelection(values: any) {
    const allSelected = values.ALL;

    console.log('Inside handleCheckbox');

    // If "All" is selected and another box is checked, uncheck "All"
    if (allSelected && (values.FirstName || values.LastName || values.MiddleName)) {
    this.reportListFG.get('filterGroup')?.patchValue(
    {
    ALL: false
    },
    { emitEvent: false } // Prevent infinite loop
    );
    }

    // If "All" is selected, ensure other checkboxes remain unchecked
    else if (allSelected) {
    console.log(allSelected, '********');
    this.reportListFG.get('filterGroup')?.patchValue(
    {
    FirstName: false,
    LastName: false,
    MiddleName: false
    },
    { emitEvent: false } // Prevent infinite loop
    );
    }
    }

    Continue reading...

Compartilhe esta Página