Skip to content

Commit 12497e5

Browse files
committed
feat(listbox): added additional focus management logic and a getSelectedValues function.
1 parent e203edc commit 12497e5

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

src/cdk-experimental/listbox/listbox.spec.ts

+5
Original file line numberDiff line numberDiff line change
@@ -659,6 +659,11 @@ describe('CdkOption and CdkListbox', () => {
659659
listboxInstance.writeValue(['arc', 'stasis']);
660660
fixture.detectChanges();
661661

662+
const selectedValues = listboxInstance.getSelectedValues();
663+
expect(selectedValues.length).toBe(2);
664+
expect(selectedValues[0]).toBe('arc');
665+
expect(selectedValues[1]).toBe('stasis');
666+
662667
expect(optionElements[0].hasAttribute('aria-selected')).toBeFalse();
663668
expect(optionElements[1].hasAttribute('aria-selected')).toBeFalse();
664669

src/cdk-experimental/listbox/listbox.ts

+15
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,10 @@ export class CdkOption<T = unknown> implements ListKeyManagerOption, Highlightab
176176
}
177177
}
178178

179+
getElementRef() {
180+
return this._elementRef;
181+
}
182+
179183
/** Sets the active property to true to enable the active css class. */
180184
setActiveStyles() {
181185
this._active = true;
@@ -273,6 +277,7 @@ export class CdkListbox<T> implements AfterContentInit, OnDestroy, OnInit, Contr
273277
@Input('parentPanel') private readonly _explicitPanel: CdkComboboxPanel;
274278

275279
constructor(
280+
private readonly _elementRef: ElementRef,
276281
@Optional() @Inject(PANEL) readonly _parentPanel?: CdkComboboxPanel<T>,
277282
) { }
278283

@@ -422,6 +427,10 @@ export class CdkListbox<T> implements AfterContentInit, OnDestroy, OnInit, Contr
422427

423428
if (!this.useActiveDescendant) {
424429
this._activeOption.focus();
430+
} else {
431+
if (document.activeElement === this._activeOption.getElementRef().nativeElement) {
432+
this._elementRef.nativeElement.focus();
433+
}
425434
}
426435
}
427436

@@ -459,6 +468,7 @@ export class CdkListbox<T> implements AfterContentInit, OnDestroy, OnInit, Contr
459468
/** Updates the key manager's active item to the given option. */
460469
setActiveOption(option: CdkOption<T>) {
461470
this._listKeyManager.updateActiveItem(option);
471+
this._updateActiveOption();
462472
}
463473

464474
/**
@@ -489,6 +499,11 @@ export class CdkListbox<T> implements AfterContentInit, OnDestroy, OnInit, Contr
489499
this.disabled = isDisabled;
490500
}
491501

502+
/** Returns the values of the currently selected options. */
503+
getSelectedValues(): T[] {
504+
return this._options.filter(option => option.selected).map(option => option.value);
505+
}
506+
492507
/** Selects an option that has the corresponding given value. */
493508
private _setSelectionByValue(values: T | T[]) {
494509
for (const option of this._options.toArray()) {

0 commit comments

Comments
 (0)