Disable auto focus in dialog- modal in Angular 2/ material

AngularModal DialogAngular Material2

Angular Problem Overview


I'm using dialog from angular material-2.

The problem is: I can't disable auto focus when modal-dialog is opened in iPhone or tablet especially. In iOS, it automatically focuses the first input field in the dialog!

I tried with tab index and with auto focus in other input-field it doesn't work

I'm using Angular 2 for my code, in my dialog I'm using form-control. I tried to use markasuntouched afterviewInit, but I still have the same problem !!

Angular Solutions


Solution 1 - Angular

Since @angular/[email protected] there is special option autoFocus on MatDialogConfig

/** Whether the dialog should focus the first focusable element on open. */
autoFocus?: boolean = true;

So you can use it as follows:

let dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
  width: '250px',
  data: { name: this.name, animal: this.animal },
  autoFocus: false   <============================== this line
});

Stackblitz Example

Solution 2 - Angular

I used the solution to disable auto focus when open the dialog and also avoid auto focus on the last selected button. I see that it works well for both dialog and bottom sheet control in Angular Material, see the code:

this.dialog.open(YourComponent, {
      data: inputData,
      width: '100%', 
      autoFocus: false, 
      restoreFocus: false
    });

this.matBottomSheet.open(FilePickerComponent, {
      data: inputData,
      autoFocus: false,
      restoreFocus: false});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMohamad ArbashView Question on Stackoverflow
Solution 1 - AngularyurzuiView Answer on Stackoverflow
Solution 2 - AngularToan NCView Answer on Stackoverflow