【问题标题】:Directive doesn't handle event指令不处理事件
【发布时间】:2021-02-28 10:50:00
【问题描述】:

我必须创建一个指令来处理“关键事件事件”。所以我这样做:

@Directive({
    selector: 'p-dropdown',
})
export class AccessibilityDropdownDirective implements OnDestroy {

constructor(private dropdown: Dropdown,
    private elementRef: ElementRef) {
    this.dropdownHtmlElement = this.elementRef.nativeElement as HTMLElement;
}

ngOnInit(): void {
    console.log("here")
    //  this.replaceKeyDownAction();
    // this.subscribeToDropdownShowEvent();
    // this.subscribeToDropdownHideEvent();
}

ngOnDestroy(): void {
    this.subscriptions.unsubscribe();
}

@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
    console.log(event);//here is never called
    if (event.keyCode == 13) {
        this.dropdown.show();
    }
}

如果我按下“回车”,也不会调用按键事件。调用ngonInit 中的console.log。我需要处理这个事件,有人可以帮助我吗?

【问题讨论】:

    标签: angular angular-directive


    【解决方案1】:
    @HostListener('window:keydown', ['$event'])
    onKeyDown(event: KeyboardEvent) {
        console.log(event);//here is never called
        if (event.keyCode == 13) {
            this.dropdown.show();
        }
    

    【讨论】:

    • 我需要在组件中处理而不是在窗口中。
    猜你喜欢
    • 1970-01-01
    • 2017-02-27
    • 2011-12-19
    • 2023-03-03
    • 1970-01-01
    • 2014-08-15
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多