Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function on checking a checkbox in angular 2.0

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?

like image 689
code1 Avatar asked Mar 08 '17 18:03

code1


People also ask

How do you call a function if a checkbox is checked in angular 2?

@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.

How do you checked the checkbox in angular?

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 checkbox is checked call a function?

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.

How do I check if a checkbox is checked in angular TypeScript?

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.


2 Answers

You can do this,

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

and in typescript,

yourfunc(e) {
   if(e.target.checked){        
   }
}
like image 55
Sajeetharan Avatar answered Oct 08 '22 00:10

Sajeetharan


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){        
   }
}
like image 23
Pradeep Kumar Das Avatar answered Oct 08 '22 00:10

Pradeep Kumar Das