Skip to content

Commit 77e47ac

Browse files
crisbetojelbourn
authored andcommitted
fix(bottom-sheet): not moving focus to container if autoFocus is disabled and focus was moved while animating (angular#16418)
These changes incorporate angular#16297 and angular#16221 into the bottom sheet since it follows a similar focus capturing behavior to `MatDialogContainer`. They ensure that focus is on the bottom sheet container when the animation is over, because it could've moved while we were animating. It also has an extra check to ensure that we don't move focus unnecessarily if the consumer decided to move focus themselves somewhere within the bottom sheet.
1 parent 565bd7d commit 77e47ac

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

src/material/bottom-sheet/bottom-sheet-container.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -180,15 +180,27 @@ export class MatBottomSheetContainer extends BasePortalOutlet implements OnDestr
180180
}
181181
}
182182

183-
184183
/** Moves the focus inside the focus trap. */
185184
private _trapFocus() {
185+
const element = this._elementRef.nativeElement;
186+
186187
if (!this._focusTrap) {
187-
this._focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement);
188+
this._focusTrap = this._focusTrapFactory.create(element);
188189
}
189190

190191
if (this.bottomSheetConfig.autoFocus) {
191192
this._focusTrap.focusInitialElementWhenReady();
193+
} else {
194+
const activeElement = this._document.activeElement;
195+
196+
// Otherwise ensure that focus is on the container. It's possible that a different
197+
// component tried to move focus while the open animation was running. See:
198+
// https://github.com/angular/components/issues/16215. Note that we only want to do this
199+
// if the focus isn't inside the bottom sheet already, because it's possible that the
200+
// consumer turned off `autoFocus` in order to move focus themselves.
201+
if (activeElement !== element && !element.contains(activeElement)) {
202+
element.focus();
203+
}
192204
}
193205
}
194206

0 commit comments

Comments
 (0)