Home > front end >  How to get the checked values from a checkbox in Angular?
How to get the checked values from a checkbox in Angular?

Time:07-14

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
}

CodePudding user response:

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)
  }
}
  • Related