From 22656fa21e3d2207b0884e92a1ce4449aae017b9 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Fri, 20 Jul 2018 17:11:59 +0200 Subject: [PATCH] fix(chips): losing focus if active chip is deleted (#11910) --- src/lib/chips/chip-list.spec.ts | 27 ++++++++++++++++++++++++--- src/lib/chips/chip-list.ts | 10 +++++----- 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/src/lib/chips/chip-list.spec.ts b/src/lib/chips/chip-list.spec.ts index b3cf5b95a7db..32dade78b090 100644 --- a/src/lib/chips/chip-list.spec.ts +++ b/src/lib/chips/chip-list.spec.ts @@ -320,6 +320,20 @@ describe('MatChipList', () => { manager = chipListInstance._keyManager; }); + it('should maintain focus if the active chip is deleted', () => { + const secondChip = fixture.nativeElement.querySelectorAll('.mat-chip')[1]; + + secondChip.focus(); + fixture.detectChanges(); + + expect(chipListInstance.chips.toArray().findIndex(chip => chip._hasFocus)).toBe(1); + + dispatchKeyboardEvent(secondChip, 'keydown', DELETE); + fixture.detectChanges(); + + expect(chipListInstance.chips.toArray().findIndex(chip => chip._hasFocus)).toBe(1); + }); + describe('when the input has focus', () => { it('should not focus the last chip when press DELETE', () => { @@ -1073,15 +1087,22 @@ class StandardChipList { Add a chip - Chip 1 - Chip 1 - Chip 1 + {{chip}} ` }) class FormFieldChipList { + chips = ['Chip 0', 'Chip 1', 'Chip 2']; + + remove(chip: string) { + const index = this.chips.indexOf(chip); + + if (index > -1) { + this.chips.splice(index, 1); + } + } } diff --git a/src/lib/chips/chip-list.ts b/src/lib/chips/chip-list.ts index adbb703781a0..caf8f90b0d07 100644 --- a/src/lib/chips/chip-list.ts +++ b/src/lib/chips/chip-list.ts @@ -238,8 +238,7 @@ export class MatChipList extends _MatChipListMixinBase implements MatFormFieldCo /** Whether any chips or the matChipInput inside of this chip-list has focus. */ get focused(): boolean { - return this.chips.some(chip => chip._hasFocus) || - (this._chipInput && this._chipInput.focused); + return (this._chipInput && this._chipInput.focused) || this.chips.some(chip => chip._hasFocus); } /** @@ -515,13 +514,14 @@ export class MatChipList extends _MatChipListMixinBase implements MatFormFieldCo * one. */ protected _updateFocusForDestroyedChips() { - let chipsArray = this.chips; + const chipsArray = this.chips.toArray(); - if (this._lastDestroyedIndex != null && chipsArray.length > 0 && this.focused) { + if (this._lastDestroyedIndex != null && chipsArray.length > 0 && (this.focused || + (this._keyManager.activeItem && chipsArray.indexOf(this._keyManager.activeItem) === -1))) { // Check whether the destroyed chip was the last item const newFocusIndex = Math.min(this._lastDestroyedIndex, chipsArray.length - 1); this._keyManager.setActiveItem(newFocusIndex); - let focusChip = this._keyManager.activeItem; + const focusChip = this._keyManager.activeItem; // Focus the chip if (focusChip) { focusChip.focus();