Skip to content

Commit 9e4d57c

Browse files
committed
fix(cdk/listbox): prevent form submission on click (#25858)
`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)
1 parent 48d666b commit 9e4d57c

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

src/cdk/listbox/listbox.spec.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import {fakeAsync, TestBed, tick} from '@angular/core/testing';
22
import {Component, Type} from '@angular/core';
33
import {By} from '@angular/platform-browser';
44
import {CdkListbox, CdkListboxModule, CdkOption, ListboxValueChangeEvent} from './index';
5-
import {dispatchKeyboardEvent, dispatchMouseEvent} from '../testing/private';
5+
import {dispatchFakeEvent, dispatchKeyboardEvent, dispatchMouseEvent} from '../testing/private';
66
import {
77
A,
88
B,
@@ -139,6 +139,14 @@ describe('CdkOption and CdkListbox', () => {
139139
expect(fixture.componentInstance.changedOption?.id).toBe(options[0].id);
140140
});
141141

142+
it('should prevent the default click action', () => {
143+
const {fixture, optionEls} = setupComponent(ListboxWithOptions);
144+
const event = dispatchFakeEvent(optionEls[1], 'click');
145+
fixture.detectChanges();
146+
147+
expect(event.defaultPrevented).toBe(true);
148+
});
149+
142150
it('should select and deselect range on option SHIFT + click', () => {
143151
const {testComponent, fixture, listbox, optionEls} = setupComponent(ListboxWithOptions);
144152
testComponent.isMultiselectable = true;

src/cdk/listbox/listbox.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -873,6 +873,7 @@ export class CdkListbox<T = unknown> implements AfterContentInit, OnDestroy, Con
873873
* @param option The option that was clicked.
874874
*/
875875
private _handleOptionClicked(option: CdkOption<T>, event: MouseEvent) {
876+
event.preventDefault();
876877
this.listKeyManager.setActiveItem(option);
877878
if (event.shiftKey && this.multiple) {
878879
this.triggerRange(

0 commit comments

Comments
 (0)