Material: Have option to set initial focus to Cancel in $mdDialog.confirm()

Created on 18 Jun 2015  路  11Comments  路  Source: angular/material

Currently, the dialog $mdDialog.confirm() starts off with the ok action button focused. This is potentially very dangerous if what you're confirming is a destructive action like deletion. Could we get and option to set the initial focus to the cancel button instead?

fixed

Most helpful comment

@gilad905
Let's try this code

var confirm = $mdDialog.confirm({onComplete: function afterShowAnimation() {
                        var $dialog = angular.element(document.querySelector('md-dialog'));
                        var $actionsSection = $dialog.find('md-dialog-actions');
                        var $cancelButton = $actionsSection.children()[0];
                        var $confirmButton = $actionsSection.children()[1];
                        angular.element($confirmButton).removeClass('md-focused');
                        angular.element($cancelButton).addClass('md-focused');
                        $cancelButton.focus();
            }})
.title('Delete book')
.textContent('Do you want to delete this book?')
.ariaLabel('Delete book')
.targetEvent(null)
.ok('Yes')
.cancel('No');

All 11 comments

+1, or just not have either of them focused

See md-autoFocus feature.

@ThomasBurleson, where?

@ThomasBurleson Apparently its not documented https://github.com/angular/material/issues/4737

and, if I do not want to focus on any button?

+1: please re-open, AFAIK there is no straight forward way to do this with $mdDialog.confirm() (html is on angular side so not possible to just add md-autofocus to cancel button)

+1: I agree, I also can't think of any way to set md-autofocus on $mdDialog.confirm()

@gilad905
Let's try this code

var confirm = $mdDialog.confirm({onComplete: function afterShowAnimation() {
                        var $dialog = angular.element(document.querySelector('md-dialog'));
                        var $actionsSection = $dialog.find('md-dialog-actions');
                        var $cancelButton = $actionsSection.children()[0];
                        var $confirmButton = $actionsSection.children()[1];
                        angular.element($confirmButton).removeClass('md-focused');
                        angular.element($cancelButton).addClass('md-focused');
                        $cancelButton.focus();
            }})
.title('Delete book')
.textContent('Do you want to delete this book?')
.ariaLabel('Delete book')
.targetEvent(null)
.ok('Yes')
.cancel('No');

Thanks, @quocphu, this does work.
Although isn't direct DOM manipulation from a controller kind of a bad practice? or is this not considered to be made from a controller, because afterShowAnimation runs within the mdDialog directive?

Thanks, @quocphu,
its working perfect

@quocphu thank you for the tip.
You can also use $document[0].activeElement.blur(); in the onComplete callback.

Was this page helpful?
0 / 5 - 0 ratings