Skip to content

Commit 0ed9416

Browse files
crisbetoandrewseguin
authored andcommitted
fix(dialog): don't move focus to dialog container if focus is already inside the dialog (#16297)
This is a follow-up to #16221. What we hadn't accounted for in the aforementioned PR is that the consumer may have turned off `autoFocus` so that they can handle it themselves and with our changes focus would be reset back to the container. These changes add an extra check which will ensure that focus is only moved if it's not inside the dialog already.
1 parent 93f4b58 commit 0ed9416

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

src/material/dialog/dialog-container.ts

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -132,20 +132,28 @@ export class MatDialogContainer extends BasePortalOutlet {
132132

133133
/** Moves the focus inside the focus trap. */
134134
private _trapFocus() {
135+
const element = this._elementRef.nativeElement;
136+
135137
if (!this._focusTrap) {
136-
this._focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement);
138+
this._focusTrap = this._focusTrapFactory.create(element);
137139
}
138140

139-
// If were to attempt to focus immediately, then the content of the dialog would not yet be
141+
// If we were to attempt to focus immediately, then the content of the dialog would not yet be
140142
// ready in instances where change detection has to run first. To deal with this, we simply
141143
// wait for the microtask queue to be empty.
142144
if (this._config.autoFocus) {
143145
this._focusTrap.focusInitialElementWhenReady();
144146
} else {
147+
const activeElement = this._document.activeElement;
148+
145149
// Otherwise ensure that focus is on the dialog container. It's possible that a different
146150
// component tried to move focus while the open animation was running. See:
147-
// https://github.com/angular/components/issues/16215
148-
this._elementRef.nativeElement.focus();
151+
// https://github.com/angular/components/issues/16215. Note that we only want to do this
152+
// if the focus isn't inside the dialog already, because it's possible that the consumer
153+
// turned off `autoFocus` in order to move focus themselves.
154+
if (activeElement !== element && !element.contains(activeElement)) {
155+
element.focus();
156+
}
149157
}
150158
}
151159

0 commit comments

Comments
 (0)