0

I would like to attach an event listner in my component that will fire for all elements that have a specific class.

These are generated by a third party component so i cannot attach it at the point where they are created.

i would like to do effectively do the equivalent of the following jquery statement but in angular where .day is the class.

$(document).on('mousedown','.day',function(jsEvent){ 

});

Thanks

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
Piotr Stulinski
  • 9,241
  • 8
  • 31
  • 46
  • I think that in this post https://stackoverflow.com/questions/43376081/angular2-retrieve-all-elements-with-class-name can help you to get the elements, and using renderer2 you can listen the events https://angular.io/api/core/Renderer2#listen, but not sure – Eliseo Oct 01 '18 at 19:10

1 Answers1

1

You can use a Directive to attach the listener:

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '.day'
})
export class DayDirective {

    @HostListener('mousedown', ['$event'])
    yourFunction(event: Event): void { ... }

}

To wire up the Directive, you add it to the module that requires it. This could be your app module, a shared module or a feature module.

import { NgModule } from '@angular/core';

@NgModule({
  declarations: [
    DayDirective,
  ],
  ...
})
export class YourModule {}
Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144