File tree Expand file tree Collapse file tree 3 files changed +38
-1
lines changed Expand file tree Collapse file tree 3 files changed +38
-1
lines changed Original file line number Diff line number Diff line change @@ -95,6 +95,12 @@ export class MatDialogConfig<D = any> {
95
95
/** Whether the dialog should focus the first focusable element on open. */
96
96
autoFocus ?: boolean = true ;
97
97
98
+ /**
99
+ * Whether the dialog should restore focus to the
100
+ * previously-focused element, after it's closed.
101
+ */
102
+ restoreFocus ?: boolean = true ;
103
+
98
104
/** Scroll strategy to be used for the dialog. */
99
105
scrollStrategy ?: ScrollStrategy ;
100
106
Original file line number Diff line number Diff line change @@ -148,7 +148,7 @@ export class MatDialogContainer extends BasePortalOutlet {
148
148
const toFocus = this . _elementFocusedBeforeDialogWasOpened ;
149
149
150
150
// We need the extra check, because IE can set the `activeElement` to null in some cases.
151
- if ( toFocus && typeof toFocus . focus === 'function' ) {
151
+ if ( this . _config . restoreFocus && toFocus && typeof toFocus . focus === 'function' ) {
152
152
toFocus . focus ( ) ;
153
153
}
154
154
Original file line number Diff line number Diff line change @@ -1009,6 +1009,37 @@ describe('MatDialog', () => {
1009
1009
. toBe ( 'MAT-DIALOG-CONTAINER' , 'Expected dialog container to be focused.' ) ;
1010
1010
} ) ) ;
1011
1011
1012
+ it ( 'should be able to disable focus restoration' , fakeAsync ( ( ) => {
1013
+ // Create a element that has focus before the dialog is opened.
1014
+ const button = document . createElement ( 'button' ) ;
1015
+ button . id = 'dialog-trigger' ;
1016
+ document . body . appendChild ( button ) ;
1017
+ button . focus ( ) ;
1018
+
1019
+ const dialogRef = dialog . open ( PizzaMsg , {
1020
+ viewContainerRef : testViewContainerRef ,
1021
+ restoreFocus : false
1022
+ } ) ;
1023
+
1024
+ flushMicrotasks ( ) ;
1025
+ viewContainerFixture . detectChanges ( ) ;
1026
+ flushMicrotasks ( ) ;
1027
+
1028
+ expect ( document . activeElement . id )
1029
+ . not . toBe ( 'dialog-trigger' , 'Expected the focus to change when dialog was opened.' ) ;
1030
+
1031
+ dialogRef . close ( ) ;
1032
+ flushMicrotasks ( ) ;
1033
+ viewContainerFixture . detectChanges ( ) ;
1034
+ tick ( 500 ) ;
1035
+
1036
+ expect ( document . activeElement . id ) . not . toBe ( 'dialog-trigger' ,
1037
+ 'Expected focus not to have been restored.' ) ;
1038
+
1039
+ document . body . removeChild ( button ) ;
1040
+ } ) ) ;
1041
+
1042
+
1012
1043
} ) ;
1013
1044
1014
1045
describe ( 'dialog content elements' , ( ) => {
You can’t perform that action at this time.
0 commit comments