Skip to content

Commit 3fa56df

Browse files
authored
refactor(material/sidenav): Remove use of focusInitialElementWhenReady (#28683)
* refactor(material/sidenav): Remove use of focusInitialElementWhenReady * fix(material/sidenav): fix view already destroyed error
1 parent 54a3504 commit 3fa56df

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

src/material/autocomplete/autocomplete.spec.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2546,6 +2546,10 @@ describe('MDC-based MatAutocomplete', () => {
25462546
fixture.detectChanges();
25472547
await new Promise(r => setTimeout(r));
25482548
fixture.detectChanges();
2549+
await new Promise(r => setTimeout(r));
2550+
fixture.detectChanges();
2551+
await new Promise(r => setTimeout(r));
2552+
fixture.detectChanges();
25492553
};
25502554

25512555
await flushPosition();

src/material/sidenav/drawer.ts

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,8 @@ export class MatDrawer implements AfterViewInit, AfterContentChecked, OnDestroy
321321
*/
322322
readonly _modeChanged = new Subject<void>();
323323

324+
private _injector = inject(Injector);
325+
324326
constructor(
325327
private _elementRef: ElementRef<HTMLElement>,
326328
private _focusTrapFactory: FocusTrapFactory,
@@ -331,12 +333,11 @@ export class MatDrawer implements AfterViewInit, AfterContentChecked, OnDestroy
331333
@Optional() @Inject(DOCUMENT) private _doc: any,
332334
@Optional() @Inject(MAT_DRAWER_CONTAINER) public _container?: MatDrawerContainer,
333335
) {
334-
this.openedChange.subscribe((opened: boolean) => {
336+
this.openedChange.pipe(takeUntil(this._destroyed)).subscribe((opened: boolean) => {
335337
if (opened) {
336338
if (this._doc) {
337339
this._elementFocusedBeforeDrawerWasOpened = this._doc.activeElement as HTMLElement;
338340
}
339-
340341
this._takeFocus();
341342
} else if (this._isFocusWithinDrawer()) {
342343
this._restoreFocus(this._openedVia || 'program');
@@ -441,11 +442,15 @@ export class MatDrawer implements AfterViewInit, AfterContentChecked, OnDestroy
441442
return;
442443
case true:
443444
case 'first-tabbable':
444-
this._focusTrap.focusInitialElementWhenReady().then(hasMovedFocus => {
445-
if (!hasMovedFocus && typeof this._elementRef.nativeElement.focus === 'function') {
446-
element.focus();
447-
}
448-
});
445+
afterNextRender(
446+
() => {
447+
const hasMovedFocus = this._focusTrap!.focusInitialElement();
448+
if (!hasMovedFocus && typeof element.focus === 'function') {
449+
element.focus();
450+
}
451+
},
452+
{injector: this._injector},
453+
);
449454
break;
450455
case 'first-heading':
451456
this._focusByCssSelector('h1, h2, h3, h4, h5, h6, [role="heading"]');

0 commit comments

Comments
 (0)