MCPcopy Create free account
hub / github.com/angular/components / _restoreFocus

Method _restoreFocus

src/cdk/dialog/dialog-container.ts:300–343  ·  view source on GitHub ↗

Restores focus to the element that was focused before the dialog opened.

()

Source from the content-addressed store, hash-verified

298
299 /** Restores focus to the element that was focused before the dialog opened. */
300 private _restoreFocus() {
301 const focusConfig = this._config.restoreFocus;
302 let focusTargetElement: HTMLElement | null = null;
303
304 if (typeof focusConfig === 'string') {
305 focusTargetElement = this._document.querySelector(focusConfig);
306 } else if (typeof focusConfig === 'boolean') {
307 focusTargetElement = focusConfig ? this._elementFocusedBeforeDialogWasOpened : null;
308 } else if (focusConfig) {
309 focusTargetElement = focusConfig;
310 }
311
312 // We need the extra check, because IE can set the `activeElement` to null in some cases.
313 if (
314 this._config.restoreFocus &&
315 focusTargetElement &&
316 typeof focusTargetElement.focus === 'function'
317 ) {
318 const activeElement = _getFocusedElementPierceShadowDom();
319 const element = this._elementRef.nativeElement;
320
321 // Make sure that focus is still inside the dialog or is on the body (usually because a
322 // non-focusable element like the backdrop was clicked) before moving it. It's possible that
323 // the consumer moved it themselves before the animation was done, in which case we shouldn't
324 // do anything.
325 if (
326 !activeElement ||
327 activeElement === this._document.body ||
328 activeElement === element ||
329 element.contains(activeElement)
330 ) {
331 if (this._focusMonitor) {
332 this._focusMonitor.focusVia(focusTargetElement, this._closeInteractionType);
333 this._closeInteractionType = null;
334 } else {
335 focusTargetElement.focus();
336 }
337 }
338 }
339
340 if (this._focusTrap) {
341 this._focusTrap.destroy();
342 }
343 }
344
345 /** Focuses the dialog container. */
346 private _focusDialogContainer(options?: FocusOptions) {

Callers 1

ngOnDestroyMethod · 0.95

Calls 4

focusViaMethod · 0.80
focusMethod · 0.65
destroyMethod · 0.65

Tested by

no test coverage detected