Skip to content

Commit

Permalink
fix(cdk/listbox): prevent form submission on click (#25858)
Browse files Browse the repository at this point in the history
`CdkOption` can be placed on any element which means that it could cause a `form` to be submitted if it's placed on a `button`. These changes add a `preventDefault` to avoid the submission.

(cherry picked from commit ce4806a)
  • Loading branch information
crisbeto committed Oct 25, 2022
1 parent 48d666b commit 9e4d57c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/cdk/listbox/listbox.spec.ts
Expand Up @@ -2,7 +2,7 @@ import {fakeAsync, TestBed, tick} from '@angular/core/testing';
import {Component, Type} from '@angular/core';
import {By} from '@angular/platform-browser';
import {CdkListbox, CdkListboxModule, CdkOption, ListboxValueChangeEvent} from './index';
import {dispatchKeyboardEvent, dispatchMouseEvent} from '../testing/private';
import {dispatchFakeEvent, dispatchKeyboardEvent, dispatchMouseEvent} from '../testing/private';
import {
A,
B,
Expand Down Expand Up @@ -139,6 +139,14 @@ describe('CdkOption and CdkListbox', () => {
expect(fixture.componentInstance.changedOption?.id).toBe(options[0].id);
});

it('should prevent the default click action', () => {
const {fixture, optionEls} = setupComponent(ListboxWithOptions);
const event = dispatchFakeEvent(optionEls[1], 'click');
fixture.detectChanges();

expect(event.defaultPrevented).toBe(true);
});

it('should select and deselect range on option SHIFT + click', () => {
const {testComponent, fixture, listbox, optionEls} = setupComponent(ListboxWithOptions);
testComponent.isMultiselectable = true;
Expand Down
1 change: 1 addition & 0 deletions src/cdk/listbox/listbox.ts
Expand Up @@ -873,6 +873,7 @@ export class CdkListbox<T = unknown> implements AfterContentInit, OnDestroy, Con
* @param option The option that was clicked.
*/
private _handleOptionClicked(option: CdkOption<T>, event: MouseEvent) {
event.preventDefault();
this.listKeyManager.setActiveItem(option);
if (event.shiftKey && this.multiple) {
this.triggerRange(
Expand Down

0 comments on commit 9e4d57c

Please sign in to comment.