Skip to content

Commit 53ea1db

Browse files
crisbetojelbourn
authored andcommitted
fix(dialog): focus recapturing not accounting for autoFocus option (#19356)
In #18826 we added some logic to recapture focus if the user clicks on a disabled backdrop. The problem is that we didn't account for the `autoFocus` config option. Fixes #19350.
1 parent 7bc095b commit 53ea1db

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

src/material/dialog/dialog-container.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,9 +151,9 @@ export class MatDialogContainer extends BasePortalOutlet {
151151
/** Moves focus back into the dialog if it was moved out. */
152152
_recaptureFocus() {
153153
if (!this._containsFocus()) {
154-
const focusWasTrapped = this._focusTrap.focusInitialElement();
154+
const focusContainer = !this._config.autoFocus || !this._focusTrap.focusInitialElement();
155155

156-
if (!focusWasTrapped) {
156+
if (focusContainer) {
157157
this._elementRef.nativeElement.focus();
158158
}
159159
}

src/material/dialog/dialog.spec.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -983,6 +983,33 @@ describe('MatDialog', () => {
983983
expect(document.activeElement).toBe(input, 'Expected input to stay focused after click');
984984
}));
985985

986+
it('should recapture focus to the container when clicking on the backdrop with ' +
987+
'autoFocus disabled', fakeAsync(() => {
988+
dialog.open(PizzaMsg, {
989+
disableClose: true,
990+
viewContainerRef: testViewContainerRef,
991+
autoFocus: false
992+
});
993+
994+
viewContainerFixture.detectChanges();
995+
flushMicrotasks();
996+
997+
let backdrop =
998+
overlayContainerElement.querySelector('.cdk-overlay-backdrop') as HTMLElement;
999+
let container =
1000+
overlayContainerElement.querySelector('.mat-dialog-container') as HTMLInputElement;
1001+
1002+
expect(document.activeElement).toBe(container, 'Expected container to be focused on open');
1003+
1004+
container.blur(); // Programmatic clicks might not move focus so we simulate it.
1005+
backdrop.click();
1006+
viewContainerFixture.detectChanges();
1007+
flush();
1008+
1009+
expect(document.activeElement)
1010+
.toBe(container, 'Expected container to stay focused after click');
1011+
}));
1012+
9861013
});
9871014

9881015
describe('hasBackdrop option', () => {

0 commit comments

Comments
 (0)