6

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?

1
  • Can you post your component's class code? I think you should use angular data binding on the input. Commented Nov 29, 2016 at 16:59

3 Answers 3

8

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: boolean = false;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Added this and got the following error: 'Can't bind to 'ngModel' since it isn't a known property of 'input'. I've imported FormsModule in my class.
You should import FormsModule in your NgModule imports, not only in your class. angular.io/docs/ts/latest/tutorial/…
It does not work if you don't set the "name" attribute. No idea where to find the Angular version I'm using, probably Angular 5 (fresh .Net project started 2 months ago).
2

you may bind to checked property of input element like below,

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>
  <label><input type="checkbox" [checked]="checkbox1" /> Folder 1: </label>
<label><input type="checkbox" [checked]="checkbox2" /> Folder 2: </label>
  `
})
export class AppComponent { 
  name = 'Angular'; 
  checkbox1 = false;
  checkbox2 = true;
}

Here is the Plunker.

Hope this helps!!

1 Comment

The Plunker is no longer working. Gets an error: (SystemJS) XHR error (404) loading unpkg.com/rxjs/operators.js
0

You can use [value]="myVariable" in checkboxes!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.