在 Angular2 中捕获所有可点击元素?

Yuv*_*als 3 angular

我想为cursor:pointer所有(click)定义了处理程序(或绑定到点击事件)的元素添加一个css 样式。我相信在 AngularJS 上可以使用 定义 css [ng-click] { ... },Angular2/4 是否有类似的解决方法?

yur*_*zui 5

1)如果你想向所有具有(click)处理程序的元素添加一些行为,你可以创建如下指令:

@Directive({
  selector: '[click]',
  host: {
    'style': 'cursor: pointer' // or class
  }
})
export class ClickableDirective {}
Run Code Online (Sandbox Code Playgroud)

Plunker 示例

2)要捕获所有具有click处理程序的元素,我将覆盖EventManager

import { Injectable, Inject, NgZone }      from '@angular/core';
import { EventManager, EVENT_MANAGER_PLUGINS } from '@angular/platform-browser';

@Injectable()
export class MyEventManager extends EventManager {
  constructor(@Inject(EVENT_MANAGER_PLUGINS) plugins: any[], private zone: NgZone) {
    super(plugins, zone);
  }

  addEventListener(element: HTMLElement, eventName: string, handler: Function): Function {
    if(eventName === 'click') {
      element.style.cursor = 'pointer'; // or add class
    }

    return super.addEventListener(element, eventName, handler);
  }
}
Run Code Online (Sandbox Code Playgroud)

app.module.ts

  ...
  providers: [
    { provide: EventManager, useClass: MyEventManager }
  ]
})
export class AppModule {
Run Code Online (Sandbox Code Playgroud)

Plunker 示例