首页 > 解决方案 > Mapping arrow keys to switch between photos in Angular

问题描述

I have a photo viewer that I'm showing in a mat-dialog control in an Angular 6 application:

<mat-dialog-content>
    <img 
    (keydown.ArrowLeft)="previous()" 
    (keydown.ArrowRight)="next()" 
    src="{{photo.filename}}" />
</mat-dialog-content>

<mat-dialog-actions>
    <button (click)="previous()">Previous</button>
    <button (click)="next()">Next</button>
</mat-dialog-actions>

My next() and previous() functions work if I click the buttons, but I'm trying to map them to the left and right arrow keys on the keyboard, and it's not working.

What have I done wrong?

标签: angular

解决方案


您必须绑定到您的 component.ts 中的文档:

@HostListener('document:keydown.arrowleft')
previous(): {

}


@HostListener('document:keydown.arrowright')
next(): {

}

推荐阅读