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);
}
You need to handle the checkbox status while removing the item from
selectedTermsArrayarray.Update you input checkbox like below. Added an
ngModelto maintain the status of checkbox and replaceonChangeevent withngModelChange.Your
onModelChangefunction is like below.And then while removing the item from below, update the main array checkbox status like this.
Working codesandbox:-
https://codesandbox.io/s/checkbox-relationship-lc7q2?file=/src/app/app.component.ts