0

I have a button, that when clicked, navigates to another route. The relative code is:

<button (click)="goBack()" mat-button
      aria-label="Previous Screen" role="navigation">
      <mat-icon>keyboard_arrow_left</mat-icon>
</button>

And the click handler:

  goBack() {
    this.location.back();
  }

When I click the button, the route changes, but the button gains focus. Is that what am I doing wrong?

Demonstration

RaidenF
  • 3,411
  • 4
  • 26
  • 42
  • 1
    I would argue that it is good that an element with which the user interacts gains focus, and I would argue that it is good that the user is aware where the focus is. Why? Accessibility. – Theraot Nov 06 '18 at 12:29
  • This flow is natural and also user-friendly. Do you wish to change focus? – sidd Nov 06 '18 at 12:33
  • I would go with adi's solution. But its probably a bug in the angular material design library – Jesse de gans Nov 06 '18 at 12:45

2 Answers2

3

You want to be looking at the HTMLElement.blur() functionality. I'm not too familiar with Angular, but you need to have access to the event and its target in order to do so.

Something like this should work:

<button (click)="goBack($event)" mat-button
      aria-label="Previous Screen" role="navigation">
      <mat-icon>keyboard_arrow_left</mat-icon>
</button>

And for the JS:

goBack(event) {
    event.target.blur()
    this.location.back();
  }
  • Instead of using `blur()` you should move focus to the heading of the new route, or perhaps back to the top of the document. I wrote a library to take care of this: https://github.com/oaf-project/oaf-angular-router – danielnixon May 11 '19 at 07:14
2

The easiest solution would be:

button:focus {
  outline: none;
}

However, removing the outline from a button is definitely bad for accessibility. There are users who can't control a mouse, and need to be able to tab through a page with the keyboard. Removing the outline makes that very difficult. It's probably better to prevent the button from receiving focus on click.

In my opinion, calling e.preventDefault() in onMouseDown is a cleaner solution. This is certainly an accessibility friendly solution (however the solution may not be compatible with your project).

Multiple clean and accesible solutions can be found here.

Cheers!

Adrian Pop
  • 1,879
  • 5
  • 28
  • 40
  • @danielnixon Did you read my entire answer before down-voting? I clearly stated that `outline: none` is a quick solution, but it is bad for accessibility and I mentioned some cleaner solutions + a link to another SO answer with extra explanation. – Adrian Pop May 16 '19 at 13:29