2

With jquery we can do something like

$(.some-class).click(function() { alert('Hello!!');});

With Angular2 / Angular4 , I know we can have

(click)="alert('Hello!!');" 

but this mean, I have to do it for each element.

Is there a way to assign the same method to all the elements with the same class?

EDIT: I don't want to select the elements by class rather, have the same function binded to the click event for all elements with the same class.

Saad Farooq
  • 977
  • 2
  • 13
  • 26
  • 1
    Possible duplicate of [How to get DOM elements by class, id, selectors and properties](http://stackoverflow.com/questions/40759325/how-to-get-dom-elements-by-class-id-selectors-and-properties) – developer033 May 18 '17 at 14:57
  • no, this question isn't about selecting, its about binding the events to a class rather than an element. – Saad Farooq May 18 '17 at 19:45

1 Answers1

2

you can do it like below,

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

@Directive({
  selector: '.some-class'
})
export class SomeClassDirective {
  constructor(private el: ElementRef) { }
  @HostListener('click') onClick() {
    console.log('Hello');
  }
}

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>
  <div class='some-class' >added some-class css class attribute</div>
  `
})
export class AppComponent { 
  name = 'Angular'; 
}

Check this Plunker

Hope this helps!!

Madhu Ranjan
  • 17,334
  • 7
  • 60
  • 69
  • Thank you, this is exactly what I wanted. Here is the same example working with two buttons: http://plnkr.co/edit/6Ec6bHc830RhGzhew4NU?p=preview – Saad Farooq May 18 '17 at 19:51