1

i have implemented a group checkbox component as explained in this SO post: Angular how to get the multiple checkbox value?

All is working well except i have one issue, the labels of the check boxes do not trigger change events, only the actual checkbox portion. In the plunker below, try clicking both the checkbox square and the label, both trigger the checkbox and update the data model but only the checkbox portion fires a change. I suspect its something to do with the transcluded value.

See this plunker http://plnkr.co/edit/BAhzLYo9e4H8PdAt9lGR?p=preview

Code

<checkbox-group [(ngModel)]="selectedItems">
   <checkbox *ngFor="let item of availableItems" 
             [value]="item"
             (change)="onItemChange($event, item)">
             {{item}}
   </checkbox>
 </checkbox-group>
 <p>Selected items - {{selectedItems | json}}</p>
ekad
  • 14,436
  • 26
  • 44
  • 46
owlyfool
  • 337
  • 3
  • 13

2 Answers2

1

Use on click event listener instead of on change. like this

(click)="onItemChange($event, item)"
Suhel
  • 927
  • 8
  • 19
  • Brilliant, thank you! would you be able to explain why (change) was half working so i have a better understanding? – owlyfool Nov 13 '17 at 14:57
  • I think the problem is something related to the checkbox directive you are using. If you wrap up input tag in the label tag then your change event will work smoothly. Try this in your plunker – Suhel Nov 14 '17 at 07:03
0

If you are using ngModel, you can also use the (ngModelChange) event. I have some normal checkboxes <input type="checkbox"/>, and the (click) and the (change) events are never fired. With (ngModelChange), it works (should also work with other tags than <input type="checkbox"/>, if they are using ngModel):

<input type="checkbox"
       (ngModelChange)="selectAllForBatchImport($event)"
       [ngModel]="areAllEntriesChecked"/>

The $event parameter will be a boolean if ngModelChange is fired from a checkbox (instead of e.g. a MouseEvent when using (click) or (change)).

By using ngModel and ngModelChange, you split up the banana-box [(ngModel)], so that you can do the change (and maybe additional work) yourself, instead of [(ngModel)], which does a "simple" ngModelChange-update by itself.

Guntram
  • 961
  • 14
  • 19