fix(chips): losing focus if active chip is deleted (#11910)

This commit is contained in:
Kristiyan Kostadinov
2018-07-20 17:11:59 +02:00
committed by Joey Perrott
parent 275de5150c
commit e13bfe08c7
2 changed files with 29 additions and 8 deletions
+24 -3
View File
@@ -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 {
<mat-form-field>
<mat-label>Add a chip</mat-label>
<mat-chip-list #chipList>
<mat-chip>Chip 1</mat-chip>
<mat-chip>Chip 1</mat-chip>
<mat-chip>Chip 1</mat-chip>
<mat-chip *ngFor="let chip of chips" (removed)="remove(chip)">{{chip}}</mat-chip>
</mat-chip-list>
<input name="test" [matChipInputFor]="chipList"/>
</mat-form-field>
`
})
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);
}
}
}
+5 -5
View File
@@ -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();