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?
@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.
AngularJS ng-checked DirectiveThe ng-checked directive sets the checked attribute of a checkbox or a radiobutton. The checkbox, or radiobutton, will be checked if the expression inside the ng-checked attribute returns true. The ng-checked directive is necessary to be able to shift the value between true and false .
When the CheckBox is clicked, the ShowHideDiv JavaScript function is executed. Inside this function, based on whether CheckBox is checked (selected) or unchecked (unselected), the HTML DIV with TextBox is shown or hidden.
To check if a checkbox element is checked in TypeScript: Type the element as HTMLInputElement using a type assertion. Use the checked property to see if the element is checked. The property will return true if it is checked and false otherwise.
You can do this,
<input type="checkbox" id="isCheckBox" (change)="yourfunc($event)"/>
and in typescript,
yourfunc(e) {
if(e.target.checked){
}
}
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){
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With