3

I am making a Bootstrap checkbox dropdown and the options is wrapped in an <a> tag that handles the click, but I also have a <input type="checkbox"> inside the a-tag.

My problem occurs when the user is pressing on the actual checkbox instead of just the <a> element. Both are clicked and some conflict happen. The checkbox checked-state should be inverted but isn't.

In Angular1 it worked to just use preventDefault() on the checkbox-click, but in my angular2-test it stops the checkbox from updating its state.

Need help with what I am doing wrong.

<ul>
    <li *ngFor="#option of options">
    <a href="" role="menuitem" tabindex="-1" (click)="setSelected($event, option)">
        <input type="checkbox" [checked]="isSelected(option)" (click)="checkboxClick($event)" /> {{ option.name }}
    </a>
  </ul>

Plunker: https://plnkr.co/edit/6D5GQ9mnaMALNnPzf5Na

I want the same behaviour when clicking on the checkboxes as clicking on the links to the right.

3 Answers 3

14

Just add ;false to the event handler expression. Returning false results in preventDefault()

<input type="checkbox" [checked]="isSelected(option)" (click)="checkboxClick($event);false" /> {{ option.name }}

You get the same effect if you return false in checkboxClick()

Sign up to request clarification or add additional context in comments.

3 Comments

I thought that the preventDefault is default in angular2, isn't it?
This comment github.com/angular/angular/issues/7277#issuecomment-188938815 addressed to you :D says "@eesdil atm, we preventDefault on every event that gets dispatched to the WebWorker here. I don't believe we're stopping propagation though." => events that get dispatched to WebWorker
Yes, I can see, thats right. Also checked the source code and they are checking the return value of the callback and not changing it. Memory...
3

You should check this.

https://plnkr.co/edit/jyX1hGNlRk0dNsR0XMXU?p=preview

<ul>
    <li *ngFor="#option of options">
            <a href="#" role="menuitem" tabindex="-1" (click)="setSelected($event, option)">
            <input type="checkbox" [checked]="isSelected(option)" (keyup)="checkboxClick($event)" /> {{ option.name }}
            </a>
     </li>
</ul>

1 Comment

Yes. Thank you. So I suppose the solution was to drop the "preventDefault" from the <a click event and instead add # to href="" to make it work.
0

Why don't you use event.stopPropagation()? It is stopping the click to propagate from checkbox to the a click handler...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.