Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the checked values from a checkbox in Angular?

A dynamic checkbox is created from the list of cartoonData. On selecting each cartoon in a checkbox, I need to read the values in typescript function.

In HTML  File

<div *ngFor="let cartoon of cartoonsData">
    <input type="checkbox" (change)="onChange($event)" />
    <label for="checkbox" >{{ cartoon.name }}</label>
</div>
In Typescript file

onChange(event){
//Code to get the checked values
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

First add a reference on the input such as #checkbox:

<div *ngFor="let cartoon of cartoonsData">
    <input #checkbox type="checkbox" (change)="onChange($event)" />
    <label for="checkbox" >{{ cartoon.name }}</label>
</div>

Next use @ViewChildren() to reference the template reference. Then wherever you need to access the checked items you can use a filter on the elements. You could also convert this to its own function if you need to use it often.

@Component()
export class MyComponent {
  @ViewChildren('checkbox') checkboxes!: QueryList<ElementRef<HTMLInputElement>>;

  onChange(event){
    const checkedItems = this.checkboxes.filter(box => box.nativeElement.checked)
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading