From f97fef647069a007e7c5634a390eaef7aa59cb73 Mon Sep 17 00:00:00 2001 From: Danny Yoo Date: Fri, 2 Feb 2024 16:41:00 -0800 Subject: [PATCH] fix(material/list): indexOf usage incorreect for active focus reset The buggy logic was using a truthiness check for checking for presence in a list, but this check needed to compare against -1 instead. This corrects a that mismanaged the tabIndex of items in the selection list: if the list of items changed, the selection list often could not be tab selected until the selection list was mouse-focused. --- src/material/list/selection-list.spec.ts | 15 +++++++++++++++ src/material/list/selection-list.ts | 2 +- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/material/list/selection-list.spec.ts b/src/material/list/selection-list.spec.ts index fc41cfa22676..e775021169d4 100644 --- a/src/material/list/selection-list.spec.ts +++ b/src/material/list/selection-list.spec.ts @@ -1319,6 +1319,21 @@ describe('MDC-based MatSelectionList with forms', () => { .toBe(1); })); + it('should focus the first option when the list items are changed', fakeAsync(() => { + fixture.componentInstance.options = ['first option', 'second option']; + fixture.detectChanges(); + + tick(); + + const listElements = fixture.debugElement + .queryAll(By.directive(MatListOption)) + .map(optionDebugEl => optionDebugEl.nativeElement); + + expect(listElements.length).toBe(2); + expect(listElements[0].tabIndex).toBe(0); + expect(listElements[1].tabIndex).toBe(-1); + })); + it('should not mark the model as touched when the list is blurred', fakeAsync(() => { expect(ngModel.touched) .withContext('Expected the selection-list to be untouched by default.') diff --git a/src/material/list/selection-list.ts b/src/material/list/selection-list.ts index 7eee169597a0..bf96ffdebba5 100644 --- a/src/material/list/selection-list.ts +++ b/src/material/list/selection-list.ts @@ -429,7 +429,7 @@ export class MatSelectionList this._items.changes.pipe(takeUntil(this._destroyed)).subscribe(() => { const activeItem = this._keyManager.activeItem; - if (!activeItem || !this._items.toArray().indexOf(activeItem)) { + if (!activeItem || this._items.toArray().indexOf(activeItem) === -1) { this._resetActiveOption(); } });