Angular 2 Checkbox preventDefault

这一生的挚爱 提交于 2021-01-27 13:40:29

问题


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.


回答1:


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>



回答2:


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()




回答3:


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



来源:https://stackoverflow.com/questions/36017793/angular-2-checkbox-preventdefault

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!