admin管理员组文章数量:1389758
I have a boolean variable which is by default false. So now, I want the variable to bee 'true' when a key is pressed and 'false' the key is released.
Example: When I press the shift key, the declared variable should return true and when I released it, the variable should return false.
I know Angular JS has two keyboard events (keydown and Keyup) but as long as I know, in most cases, they're only used with 'input' fields. So is there an alternative to utilize the methods without an input field?
I have a boolean variable which is by default false. So now, I want the variable to bee 'true' when a key is pressed and 'false' the key is released.
Example: When I press the shift key, the declared variable should return true and when I released it, the variable should return false.
I know Angular JS has two keyboard events (keydown and Keyup) but as long as I know, in most cases, they're only used with 'input' fields. So is there an alternative to utilize the methods without an input field?
Share Improve this question edited May 11, 2020 at 11:31 Hashmat asked Oct 7, 2019 at 12:02 HashmatHashmat 7671 gold badge8 silver badges18 bronze badges 02 Answers
Reset to default 4@HostListener('window:keyup', ['$event'])
keyEvent(event: KeyboardEvent) {
console.log(event);
}
@HostListener('window:keydown', ['$event'])
keyEvent(event: KeyboardEvent) {
console.log(event);
}
I would use @HostListener decorator within your ponent:
import { HostListener } from '@angular/core';
@Component({
...
})
export class AppComponent {
@HostListener('document:keypress', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
this.key = event.key;
}
}
Put your conditions inside that block & you'll be gtg. There exists other ways too just so you know.
版权声明:本文标题:javascript - How can I detect when a key is pressed or released in Angular 'without input'? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744594034a2614667.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论