Components: Autocomplete focus when inside a dialog

Created on 23 Oct 2017  路  8Comments  路  Source: angular/components

Bug, feature request, or proposal:

Bug

What is the expected behavior?

When opening a dialog the autocomplete doesn't have focus.
Expected: https://angular-qgx8sh.stackblitz.io/

What is the current behavior?

When opening a dialog my autocomplete get focussed.

What are the steps to reproduce?

Just open a dialog with data of the states in it:
this.dialog.open(SlideInToolbar, { width: '150px', data: { states: this.states } });

And inside the dialog an autocomplete with:
<mat-option *ngFor="let item of data.states" [value]="item.name">

https://angular-omzvev.stackblitz.io/

What is the use-case or motivation for changing an existing behavior?

I want to implement a autocomplete in a dialog without focus.

Which versions of Angular, Material, OS, TypeScript, browsers are affected?

Angular: 4.4.4
Material: 2.0.0-beta.12

Most helpful comment

Depending on your situation, a better solution may be to add cdk-focus-initial to whichever element you want to focus first.

<div mat-dialog-content cdk-focus-initial> ... </div>

https://stackblitz.com/edit/angular-tksjrg?file=app%2Ftoolbar.html

All 8 comments

I'm having exactly the same issue - not that that helps you as I haven't found a workaround yet. Sorry

This is working by design.

https://github.com/angular/material2/blob/master/src/lib/dialog/dialog-container.ts#L150

When the dialog opens it needs to switch the focus from the button that initiated the dialog the a focusable element in the dialog ( your input in this case ).

You can get around this by adding tabindex="-1" to the input like so: https://stackblitz.com/edit/angular-rrfabk

Cheers this works for me.

Workaround does work a bit of a hack as it's a shame this then means the autocomplete cannot be tabbed to

Restores focus to the element that was focused before the dialog opened. This kind is false in this situation but yeah I agree it's a workaround.

Depending on your situation, a better solution may be to add cdk-focus-initial to whichever element you want to focus first.

<div mat-dialog-content cdk-focus-initial> ... </div>

https://stackblitz.com/edit/angular-tksjrg?file=app%2Ftoolbar.html

That's great thank you!
Weirdly for me I have to put it on a different control (rather than the content div tag like in your example) otherwise the focus is initially on the original page where the the dialog was called from. But that's fine it's definitely a better solution for me - thanks again!

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

_This action has been performed automatically by a bot._

Was this page helpful?
0 / 5 - 0 ratings