0
votes

I have a few checkboxes. Some of them are selected by default on the basis of data from the database. A user can unselect the selected checkboxes or select the unselected ones. Is there any way to get the list of only those checkbox values which were toggled(this list can be produced on the click of the button once the user finally decide which checkboxes are to be toggled) ?

<ul>
    <li *ngFor="let file of files">
       <input type="checkbox" ng-selected = "file.isPresent"> {{file.type}}
    </li>
</ul>


 <button (click)="getToggledCheckboxValues()"> Get Value </button>

If the file is present already then the checkbox will be checked by default.

1

1 Answers

0
votes

I will create an second array based on the files's one with default false values

toggledFiles = Array(this.files.length).fill(false);

Then add a change method for each checkbox like this

<ul>
  <li *ngFor="let file of files; let i = index">
    <input type="checkbox" (change)="onChange($event,i)" [checked]="file.isPresent"> {{file.type}}
  </li>
</ul>

And finally, just toggle the boolean value on your new array each time you toggle the corresponding checkbox's value

onChange(event, index) {
  this.toggledFiles[index] = !this.toggledFiles[index];
}

Here is a stackblitz to show you how it works.

On the example I directly show the toggle for each checkbox but you can keep it in your array and use it when you click on your getToggledCheckboxValues() button.