Search code examples
angularcheckboxcheckedunchecked

i want to uncheck a checkbox on remove filed using splice


this is my html file: The terms i got from api. On selection of checkbox , it will show selected value in selectedTermsArray.

 <span class="suggestermsSpan" >Suggested terms </span> <br>
    <div *ngFor="let list of TermsArray" >      
       <input name="checkboxName" class="checkmark" id="checkbox1" type="checkbox" value="{{list.Name}}" (change)="$event.target.checked? (isfrmChecked = true) : isfrmChecked = false; onCheckboxSelected($event,isfrmChecked);">
         {{list.Name}}
    </div>
</div>

this is also my html file:

the terms that are selected on checkbox selection of above html code. When I click on remove field value close icon. value is removed from selectedtermsArray. But, checkbox is not getting unchecked.

<div>
   <div *ngFor="let selectedValue of selectedTermsArray ; let i = index" ">     
      
     <span>{{selectedValue}}</span>

                                       
   </div>
</div>


this is my ts file..


 selectedTermsArray: string[] = [];
 isfrmChecked:any;

 onCheckboxSelected(event: any, isChecked: boolean)
 {
   if (isChecked) {
     this.selectedTermsArray.push(event.target.value);
   }
   else {
     let index = this.selectedTermsArray.indexOf(event.target.value);
     this.selectedTermsArray.splice(index, 1);
   }
 }

 removeField(index) {
         this.selectedTermsArray.splice(index, 1);
 }

Solution

  • You need to handle the checkbox status while removing the item from selectedTermsArray array.

    Update you input checkbox like below. Added an ngModel to maintain the status of checkbox and replace onChange event with ngModelChange.

    <div *ngFor="let list of TermsArray">
        <input
          name="checkboxName"
          class="checkmark"
          id="checkbox1"
          type="checkbox"
          value="{{list.Name}}"
          [(ngModel)]="list.isChecked"
          (ngModelChange)="onModelChange($event,list.Name)"
        />
        {{list.Name}}
    </div>
    

    Your onModelChange function is like below.

    onModelChange(isChecked, value) {
        if (isChecked) {
          this.selectedTermsArray.push(value);
        } else {
          let index = this.selectedTermsArray.indexOf(value);
          this.selectedTermsArray.splice(index, 1);
        }
    }
    

    And then while removing the item from below, update the main array checkbox status like this.

    removeField(index, value) {
        this.selectedTermsArray.splice(index, 1);
        this.TermsArray.map((x) => {
          if (x.Name === value) {
            x.isChecked = false;
          }
        });
    }
    

    Working codesandbox:-

    https://codesandbox.io/s/checkbox-relationship-lc7q2?file=/src/app/app.component.ts