Skip to content

fix(experimental/dialog): not moving focus to container if autoFocus is disabled and focus was moved while animating #16446

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions src/cdk-experimental/dialog/dialog-container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export class CdkDialogContainer extends BasePortalOutlet implements OnDestroy {
private _elementFocusedBeforeDialogWasOpened: HTMLElement | null = null;

/** The class that traps and manages focus within the dialog. */
private _focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement, false);
private _focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement);

// @HostBinding is used in the class as it is expected to be extended. Since @Component decorator
// metadata is not inherited by child classes, instead the host binding data is defined in a way
Expand Down Expand Up @@ -216,6 +216,8 @@ export class CdkDialogContainer extends BasePortalOutlet implements OnDestroy {
* focus the dialog instead.
*/
private _autoFocusFirstTabbableElement() {
const element = this._elementRef.nativeElement;

// If were to attempt to focus immediately, then the content of the dialog would not yet be
// ready in instances where change detection has to run first. To deal with this, we simply
// wait for the microtask queue to be empty.
Expand All @@ -224,9 +226,20 @@ export class CdkDialogContainer extends BasePortalOutlet implements OnDestroy {
// If we didn't find any focusable elements inside the dialog, focus the
// container so the user can't tab into other elements behind it.
if (!hasMovedFocus) {
this._elementRef.nativeElement.focus();
element.focus();
}
});
} else {
const activeElement = this._document.activeElement;

// Otherwise ensure that focus is on the dialog container. It's possible that a different
// component tried to move focus while the open animation was running. See:
// https://github.com/angular/components/issues/16215. Note that we only want to do this
// if the focus isn't inside the dialog already, because it's possible that the consumer
// turned off `autoFocus` in order to move focus themselves.
if (activeElement !== element && !element.contains(activeElement)) {
element.focus();
}
}
}

Expand Down