【问题标题】:How can I verify event (click) binding through an attribute directive?如何通过属性指令验证事件(单击)绑定?
【发布时间】:2019-01-29 03:32:06
【问题描述】:

我目前正在处理一些共享代码,这些代码需要可供无法使用鼠标导航的用户访问。有很多元素的点击事件绑定到处理程序。

<div ngFor="let user of users">
    <div class="link" (click)="addOrEditUser(user.Id)">{{ user.Name }}</div>
</div>

因为这些元素需要同时支持点击和按键事件,所以我定义了以下指令来帮助我仅在用户按下“Enter”键时触发点击处理程序。

import { Directive, ElementRef, OnDestroy, HostListener, HostBinding, Output, EventEmitter, OnInit } from '@angular/core';

@Directive({
    selector: '[keyboardClick]',
})
export class KeyboardClickDirective implements OnDestroy, OnInit {
    eventListenerRef: any;
    @HostBinding('attr.tabindex') tabIndexValue: number;

    @Output('click')
    emmiter = new EventEmitter();

    constructor(private elementRef: ElementRef) {
        console.log('this should have a click event', elementRef);
    }

    ngOnInit(): void {
        if (!this.tabIndexValue) this.tabIndexValue = 0;
    }

    @HostListener('keydown', ['$event'])
    enterPressed(e: KeyboardEvent) {
        if (e.key === 'Enter') {
            this.emmiter.emit(e);
        }
    }

    ngOnDestroy(): void {}
}

我必须这样做,因为我无法重构 click 事件的所有单个处理程序以支持 keypressed。

现在我的模板看起来有点像这样:

<div ngFor="let user of users">
    <div class="link" (click)="addOrEditUser(user.Id)" keyboardClick>{{ user.Name }}</div>
</div>

我的代码可以满足我的需要,但如果元素没有点击绑定,我想抛出一个错误。

TL;DR
这应该会引发错误:

<div ngFor="let user of users">
    <div class="link" keyboardClick>{{ user.Name }}</div>
</div>

这不应该引发错误:

<div ngFor="let user of users">
    <div class="link" (click)="addOrEditUser(user.Id)" keyboardClick>{{ user.Name }}</div>
</div>

【问题讨论】:

    标签: angular


    【解决方案1】:

    我认为您只需要捕获键盘点击事件。

    <div ngFor="let user of users">
        <div class="link" (keyboardClick)="addOrEditUser($event)">{{ user.Name }}</div>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2013-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      • 2015-03-15
      相关资源
      最近更新 更多