Roka545 Roka545 - 1 year ago 269
TypeScript Question

Get checkbox value from HTML in Angular 2 typescript.

I have two checkboxes in my html as follows:

<label><input type="checkbox" id="checkbox1" /> Folder 1: </label>
<label><input type="checkbox" id="checkbox2" /> Folder 2: </label>

but I'm unsure of how to retrieve the checkbox values inside my Typescript file. I know I can accomplish this by calling a separate function for each checkbox and changing a value within my typescript. However, that doesn't seem like the best way - if I had ten different checkboxes then I would need 10 different functions in my typescript.

Is there a simply way to get whether the checkbox is on or off based on the id? Is there a better way than that?

Answer Source

If you want to two-way-bind the checkbox, you should use ngModel binding.

 <input type="checkbox" [(ngModel)]="checkBoxValue" />

and in your component's class:

export class AppComponent { 
  checkboxValue: bool = false;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download