Skip to content

Commit 6a6712d

Browse files
authored
fix(material/chips): restoring focus to last chip when pressing backspace (#23136)
In #19700 a flag was introduced whose purpose was to indicate whether focus should be moved from the input to the chips when pressing backspace. The problem is that the flag was only being updated on key presses and on init which means that the state will be incorrect if the value changes programmatically after init. Fixes #23128.
1 parent 88d68ff commit 6a6712d

File tree

4 files changed

+29
-0
lines changed

4 files changed

+29
-0
lines changed

src/material-experimental/mdc-chips/chip-grid.spec.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -542,6 +542,20 @@ describe('MDC-based MatChipGrid', () => {
542542
// It focuses the last chip
543543
expectLastCellFocused();
544544
});
545+
546+
it('should not focus the last chip when pressing BACKSPACE on a non-empty input', () => {
547+
const nativeInput = fixture.nativeElement.querySelector('input');
548+
nativeInput.value = 'hello';
549+
nativeInput.focus();
550+
fixture.detectChanges();
551+
552+
expectNoCellFocused();
553+
554+
dispatchKeyboardEvent(nativeInput, 'keydown', BACKSPACE);
555+
fixture.detectChanges();
556+
557+
expectNoCellFocused();
558+
});
545559
});
546560
});
547561

src/material-experimental/mdc-chips/chip-input.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,7 @@ export class MatChipInput implements MatChipTextControl, AfterContentInit, OnCha
203203

204204
_focus() {
205205
this.focused = true;
206+
this._focusLastChipOnBackspace = this.empty;
206207
this._chipGrid.stateChanges.next();
207208
}
208209

src/material/chips/chip-input.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,7 @@ export class MatChipInput implements MatChipTextControl, OnChanges, OnDestroy, A
189189

190190
_focus() {
191191
this.focused = true;
192+
this._focusLastChipOnBackspace = this.empty;
192193
this._chipList.stateChanges.next();
193194
}
194195

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -566,6 +566,19 @@ describe('MatChipList', () => {
566566
expect(manager.activeItemIndex).toEqual(chips.length - 1);
567567
});
568568

569+
it('should not focus the last chip when pressing BACKSPACE on a non-empty input', () => {
570+
const nativeInput = fixture.nativeElement.querySelector('input');
571+
nativeInput.value = 'hello';
572+
nativeInput.focus();
573+
fixture.detectChanges();
574+
expect(manager.activeItemIndex).toBe(-1);
575+
576+
dispatchKeyboardEvent(nativeInput, 'keydown', BACKSPACE);
577+
fixture.detectChanges();
578+
579+
expect(manager.activeItemIndex).toBe(-1);
580+
});
581+
569582
});
570583
});
571584

0 commit comments

Comments
 (0)