Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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

This is my functionality,

  • I have a checkbox, on clicking this checkbox I ask a user to enter
    his/her email and press a submit button. After user presses the
    submit button I show a pop-up saying your email has been saved. And I hide the text box and the submit button. Along with this I want to uncheck the checkbox that user checked at first place to enter the email.

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 :(

like image 727
sunny arya Avatar asked Feb 06 '23 18:02

sunny arya


1 Answers

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

like image 151
Günter Zöchbauer Avatar answered Feb 13 '23 06:02

Günter Zöchbauer