0

I can attach click event in angular like this

<span (click)="showInfo()" class="info-span"><span>

But I have 20 spans like this, so is there any centralized way to attach the click event with the class name info-span in angular like we can do with jquery like this?

$('.info-span').click(function(){});

Or I have to repeat this (click)="showInfo()" in all the spans?

Pawan Nogariya
  • 8,330
  • 12
  • 52
  • 105

3 Answers3

1

Use ngFor to loop 20 times on span. Here you don't need to write it 20 times.

I am not sure if you need any specific data for each span or click function, i am assuming everything is the same.

 <span (click)="showInfo($event)" class="info-span" *ngFor="let i of [].constructor(20)">A<span>
Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48
  • You assumed I have 20 spans under same parent and with all following same settings. But they are independent spans in different areas of page and so cannot be created by ngFor – Pawan Nogariya Mar 01 '21 at 13:01
  • ok, I got it. Then there might be one option by creating a directive(if DOM manipulation is there in click function) or component with a span and click functionality and use that everywhere you want. It will reduce code duplication. – Kaustubh Khare Mar 02 '21 at 05:25
0

This is very similar to what was asked here

You global event handler to some container of these spans and then you check the source element in the event object.

This is not particular from angular, It can run here here in a code snippet

document.body.addEventListener('click', ($event) => {
  if($event.srcElement.classList.contains('red')){
    alert('red');
  }
})
.green {
  background-color: #008000;
  color: white;
}
.red {
  background-color: #800000;
  color: white;
  cursor: pointer;
}
<span class="green">A</span>
<span class="red">B</span>
<span class="green">C</span>
<span class="red">D</span>
<span class="green">E</span>
<span class="red">F</span>
<span class="red">G</span>
Bob
  • 13,867
  • 1
  • 5
  • 27
-1

The best way to solve this method is to pass the id or event as a parameter to the function being called on the click event.

<span (click)="showInfo($event)" class="info-span" id="1">btn1<span>
<span (click)="showInfo($event)" class="info-span" id="2">btn2<span>
showInfo(event){
    const selectedButtonId = event.target.id;
    alert('you just clicked the btn-', selectedButtonId);
}
Srinath Kamath
  • 542
  • 1
  • 6
  • 17