sunny arya
sunny arya

Reputation: 213

Angular2 , check or uncheck a checkbox on click of a button

I have an angular2 application where I want to dynamically check or uncheck based on user action.

This is my functionality,

When I try to use this

document.getElementById("checkBoxID").checked = false;

I get a compilation error

Error:(33, 60) TS2339: Property 'checked' does not exist on type 'HTMLElement'.

I researched somewhere and found that this property could be 'selected' instead of 'checked', but even that doesn't work.

I can use a workaround of using *ngIf with a Boolean value and get two check-boxes written in my component, one with 'checked' and one with 'unchecked' and render them accordingly based on the Boolean value and keep setting the Boolean value on click of buttons, but I believe that would be the dirty solution.

Angular2 for sure would have something simpler to do this, which I am missing here :(

Upvotes: 4

Views: 14467

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658037

Two possible ways

  <button (click)="cb.click()">toggle</button>
  <input type="checkbox" #cb>
  <button (click)="isChecked = !isChecked">toggle</button>
  <input type="checkbox" [(ngModel)]="isChecked">

Plunker example

Upvotes: 8

Related Questions