2

I have an input checkbox field inside a label tag in html with bootstrap 4 and Angular 7. And i am calling a function on click on input checkbox and passing its state "($event.target.checked)" as one of the arguments. But all i receive is "undefined". On other hand if i call the function directly from input:checkbox i.e. without tag ass the parent element then it works perfectly fine. But i need the former option to work.

Case 1: ">div>

label (click)="onChange('father', $event.target.checked, 'diabetes')" class="btn btn-sm rounded-pill position-relative mb-2 mx-2"> input type="checkbox" name="diabetes" autocomplete="off"> Father /label "

Case 2: ">div>

input type="checkbox" (click)="onChange('father', $event.target.checked, 'diabetes')" name="" id="">Father /div>"

When i console both the above in my function, i receive undefined in 1st case with label outside the input field and it works just fine without label as shown in case 2 and provides true and false as results. Can anyone help me to get true and false values in case 1 also.

1 Answers1

0

That's because you listen to click eventd on your checkbox.

Intsead, you should listen to (change) event :

(change)="onChange('father', $event, 'diabetes')" 

This way, the function will be called everytime the value of the checkbox changes.

  • I have called click event on label tag in case 1 where i am not able to access the state of input field as it is a child tag of label tab. And If i apply click event or change event on input field in case 1, then the event is not even fired at all. – Akshat Sharma May 29 '19 at 06:54
  • Did you read my answer ? You don't use the click event, you use the change event. –  May 29 '19 at 06:55
  • yes i did read ur reply.. and i applied the same to my code.. it still doesn't work... the event is not even fired at all.. – Akshat Sharma May 29 '19 at 07:10
  • Because your labels should have `for="checkboxID"` attributes to bind them to the checkboxes. –  May 29 '19 at 07:14
  • When we use input field inside a label, we dont need to use for attribute.. the label tag is already connected with the input field.. still i tried ur approach.. didn't work – Akshat Sharma May 29 '19 at 07:40
  • And seeing your image, I can see the labels aren't in the checkbox. If it doesn't work, then please provide a [mcve] of your issue. –  May 29 '19 at 07:42
  • I have completed the task to firing the event of input:checkbox.. the only part remains is i m not able to apply active class of pink color on the label or checkbox as shown in the image.. and i have somewhere around 40 checkbox, so i dnt think this would be a great idea to create multiple boolean variables and apply ngClass based on them. any shorter way? – Akshat Sharma May 29 '19 at 08:05
  • @AkshatSharma sure, once you provide a [mcve] I would gladly find another way of doing so. –  May 29 '19 at 08:13