Yuvals
Yuvals

Reputation: 3266

Catching all clickable elements in Angular2?

I want to add a cursor:pointer css style to all elements that have (click) handler defined (or have binding to click events). I believe that on AngularJS it was possible to define a css using [ng-click] { ... }, is there a similar workaround for Angular2/4?

Upvotes: 3

Views: 519

Answers (2)

yurzui
yurzui

Reputation: 214175

1) If you want to add some behavior to all elements that have (click) handler you can create directive like:

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

Plunker Example

2) To catch all element that have click handler i would override 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);
  }
}

app.module.ts

  ...
  providers: [
    { provide: EventManager, useClass: MyEventManager }
  ]
})
export class AppModule {

Plunker Example

Upvotes: 5

Zach Newburgh
Zach Newburgh

Reputation: 564

If I understood correctly, adding [style.cursor]="'pointer'" to the element should do the trick.

But it might be a better to add a 'clickable' class and have the following defined in your stylesheet:

.clickable { cursor: pointer; }

From what I can tell, Angular doesn't add anything onto the element's HTML when adding (click).

Upvotes: -1

Related Questions