cacev000
cacev000

Reputation: 329

Remove focus from mat-slide-toggle

I have been testing angular material for awhile but i just ran into an issue with the slide toggle component and listening to keyboard events after clicking in the slide toggle component.

HTML file

<mat-slide-toggle color="accent" [checked]="likeChecked" (change)="selectedOpt('like')">
    Like
</mat-slide-toggle>
<mat-slide-toggle color="primary" [checked]="dislikeChecked" (change)="selectedOpt('dislike')">
    Dislike
</mat-slide-toggle>

Component.ts file

selectedOpt(option) {
    if(option === 'like'){
        this.positiveChecked = true;
        this.neutralChecked = false;
    } else {
        this.positiveChecked = false;
        this.neutralChecked = true;
    }
}

So whenever i click on the like or dislike slide toggle component. the component gets focused and it doesn't let the program listen to keyboard events until i click anywhere else in the program.

How can i unfocus or blur after clicking the slide toggle component programmatically? In order to listen for keyboard events

Upvotes: 0

Views: 2259

Answers (1)

G. Tranter
G. Tranter

Reputation: 17908

By default, hotkeys doesn't fire events when certain elements have focus. MatSlideToggle uses an input element internally, and that is one of the elements. But you can force hotkeys to fire for specific elements. This works in your StackBlitz:

this._hotkeysService.add(new Hotkey('right', (event: KeyboardEvent): boolean => {
  console.log('right arrow pressed');
  return false;
}, ['INPUT'], 'Move to next slide'));

(see this for details - they have another workaround as well but that doesn't seem to work with the slide toggle)

The problem though, is that this affects all inputs (including the ones used internally by the radio buttons) so this might adversely affect other things depending on what key events you "take over".

I suspect that hotkeys isn't a great solution for use with Angular Material and maybe Angular @Components in general (at least ones that use native input, textarea, and select elements internally).

Upvotes: 1

Related Questions