10

I am currently using angular 2.0. In HTML, I have a checkbox, the code is as mentioned below.

<div style="margin-left:15px;">
            <label>Draw</label>
            <input id="isCheckBox" type="checkbox" checked="checked">
</div>

How to call a function only if a checkbox is checked in typescript file?

2 Answers 2

31

You can do this,

<input type="checkbox"  id="isCheckBox" (change)="yourfunc($event)"/>

and in typescript,

yourfunc(e) {
   if(e.target.checked){        
   }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hello, I use the same thing, but I got this error : "Cannot read property 'checked' of undefined"
@SoukainaElHayouni Make the code as below, it will work. yourfunc(e) { if(e.checked){ } } please remove the target property from the code.It worked for me.
@ADARSHK Thank you for your reply! I solved the problem.
1

You can use currentTarget if target won't work,

<input type="checkbox"  id="isCheckBox" (change)="yourfunc($event)"/>

and in typescript,

yourfunc(e) {
   if(e.currentTarget.checked){        
   }
}

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.