diff --git a/src/lib/chips/chip-list.ts b/src/lib/chips/chip-list.ts index c5d4f9cba617..46a1fa36f7a4 100644 --- a/src/lib/chips/chip-list.ts +++ b/src/lib/chips/chip-list.ts @@ -437,7 +437,11 @@ export class MatChipList extends _MatChipListMixinBase implements MatFormFieldCo * Implemented as part of MatFormFieldControl. * @docs-private */ - onContainerClick() { this.focus(); } + onContainerClick(event: MouseEvent) { + if (!this._originatesFromChip(event)) { + this.focus(); + } + } /** * Focuses the the first non-disabled chip in this chip list, or the associated input when there @@ -739,4 +743,19 @@ export class MatChipList extends _MatChipListMixinBase implements MatFormFieldCo } }); } + + /** Checks whether an event comes from inside a chip element. */ + private _originatesFromChip(event: Event): boolean { + let currentElement = event.target as HTMLElement | null; + + while (currentElement && currentElement !== this._elementRef.nativeElement) { + if (currentElement.classList.contains('mat-chip')) { + return true; + } + + currentElement = currentElement.parentElement; + } + + return false; + } } diff --git a/src/lib/chips/chip.spec.ts b/src/lib/chips/chip.spec.ts index 58f4e0e1079a..9a0328f3df95 100644 --- a/src/lib/chips/chip.spec.ts +++ b/src/lib/chips/chip.spec.ts @@ -1,6 +1,6 @@ import {Directionality} from '@angular/cdk/bidi'; import {BACKSPACE, DELETE, SPACE} from '@angular/cdk/keycodes'; -import {createKeyboardEvent} from '@angular/cdk/testing'; +import {createKeyboardEvent, dispatchFakeEvent} from '@angular/cdk/testing'; import {Component, DebugElement} from '@angular/core'; import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; @@ -132,6 +132,24 @@ describe('Chips', () => { expect(testComponent.chipRemove).toHaveBeenCalledWith({chip: chipInstance}); }); + + it('should not prevent the default click action', () => { + const event = dispatchFakeEvent(chipNativeElement, 'click'); + fixture.detectChanges(); + + expect(event.defaultPrevented).toBe(false); + }); + + it('should prevent the default click action when the chip is disabled', () => { + chipInstance.disabled = true; + fixture.detectChanges(); + + const event = dispatchFakeEvent(chipNativeElement, 'click'); + fixture.detectChanges(); + + expect(event.defaultPrevented).toBe(true); + }); + }); describe('keyboard behavior', () => { diff --git a/src/lib/chips/chip.ts b/src/lib/chips/chip.ts index 86c1b8a3b5ae..c39a39c3e10e 100644 --- a/src/lib/chips/chip.ts +++ b/src/lib/chips/chip.ts @@ -326,15 +326,13 @@ export class MatChip extends _MatChipMixinBase implements FocusableOption, OnDes } } - /** Ensures events fire properly upon click. */ + /** Handles click events on the chip. */ _handleClick(event: Event) { - // Check disabled if (this.disabled) { - return; + event.preventDefault(); + } else { + event.stopPropagation(); } - - event.preventDefault(); - event.stopPropagation(); } /** Handle custom key presses. */