Anmol Jain
Anmol Jain

Reputation: 411

Get list of toggled checkboxes : Angular

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.

Upvotes: 0

Views: 446

Answers (1)

Alexis
Alexis

Reputation: 1784

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.


Second approach following your comment (Stackblitz edited too)

Create an empty array and append each new toggled checkbox.

onChange(event, index) {
  const indexFound = this.toggledFiles.indexOf(index);
  if (indexFound != -1) {
    this.toggledFiles.splice(indexFound, 1);
  } else {
    this.toggledFiles.push(index);
  }
}

If you want to keep the checkbox as toggled if it has been toggled once, even if user reset the value to started one, just remove the if condition and always push the index in the array

Upvotes: 1

Related Questions