Skip to content

Commit 5fb6125

Browse files
crisbetojelbourn
authored andcommitted
fix(chips): focus lost if last chip is deleted (#15344)
Fixes the user's focus being lost if they the last chip in a list. Fixes #15338.
1 parent 07e8028 commit 5fb6125

File tree

2 files changed

+20
-13
lines changed

2 files changed

+20
-13
lines changed

src/material/chips/chip-list.spec.ts

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -146,16 +146,6 @@ describe('MatChipList', () => {
146146
expect(manager.activeItemIndex).toBe(0);
147147
});
148148

149-
it('should watch for chip focus', () => {
150-
let array = chips.toArray();
151-
let lastIndex = array.length - 1;
152-
let lastItem = array[lastIndex];
153-
lastItem.focus();
154-
fixture.detectChanges();
155-
156-
expect(manager.activeItemIndex).toBe(lastIndex);
157-
});
158-
159149
it('should watch for chip focus', () => {
160150
let array = chips.toArray();
161151
let lastIndex = array.length - 1;
@@ -238,6 +228,18 @@ describe('MatChipList', () => {
238228
expect(chipListInstance._keyManager.activeItemIndex).toEqual(-1);
239229
});
240230

231+
it('should focus the list if the last focused item is removed', () => {
232+
testComponent.chips = [0];
233+
234+
spyOn(chipListInstance, 'focus');
235+
chips.last.focus();
236+
237+
testComponent.chips.pop();
238+
fixture.detectChanges();
239+
240+
expect(chipListInstance.focus).toHaveBeenCalled();
241+
});
242+
241243
it('should move focus to the last chip when the focused chip was deleted inside a' +
242244
'component with animations', fakeAsync(() => {
243245
fixture.destroy();

src/material/chips/chip-list.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -526,9 +526,14 @@ export class MatChipList extends _MatChipListMixinBase implements MatFormFieldCo
526526
* key manager state and focus the next closest chip.
527527
*/
528528
protected _updateFocusForDestroyedChips() {
529-
if (this._lastDestroyedChipIndex != null && this.chips.length) {
530-
const newChipIndex = Math.min(this._lastDestroyedChipIndex, this.chips.length - 1);
531-
this._keyManager.setActiveItem(newChipIndex);
529+
// Move focus to the closest chip. If no other chips remain, focus the chip-list itself.
530+
if (this._lastDestroyedChipIndex != null) {
531+
if (this.chips.length) {
532+
const newChipIndex = Math.min(this._lastDestroyedChipIndex, this.chips.length - 1);
533+
this._keyManager.setActiveItem(newChipIndex);
534+
} else {
535+
this.focus();
536+
}
532537
}
533538

534539
this._lastDestroyedChipIndex = null;

0 commit comments

Comments
 (0)