Launch an event when checking a checkbox in Angular2
If you add double paranthesis to the ngModel reference you get a two-way binding to your model property. That property can then be read and used in the event handler. In my view that is the most clean approach.
<input type="checkbox" [(ngModel)]="myModel.property" (ngModelChange)="processChange()" />
StackBlitz
Template: You can either use the native change
event or NgModel directive's ngModelChange
.
<input type="checkbox" (change)="onNativeChange($event)"/>
or
<input type="checkbox" ngModel (ngModelChange)="onNgModelChange($event)"/>
TS:
onNativeChange(e) { // here e is a native event
if(e.target.checked){
// do something here
}
}
onNgModelChange(e) { // here e is a boolean, true if checked, otherwise false
if(e){
// do something here
}
}
You can use ngModel
like
<input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>
To update the checkbox state by updating the property checkboxValue
in your code and when the checkbox is changed by the user addProp()
is called.
Check Demo: https://stackblitz.com/edit/angular-6-checkbox?embed=1&file=src/app/app.component.html
CheckBox: use change event to call the function and pass the event.
<label class="container">
<input type="checkbox" [(ngModel)]="theCheckbox" data-md-icheck
(change)="toggleVisibility($event)"/>
Checkbox is <span *ngIf="marked">checked</span><span
*ngIf="!marked">unchecked</span>
<span class="checkmark"></span>
</label>
<div>And <b>ngModel</b> also works, it's value is <b>{{theCheckbox}}</b></div>