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?

1
  • Write span with click and loop over it. Try to use angular way instead of going with jquery way. Commented Mar 1, 2021 at 11:59

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

2 Comments

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
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.
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>

Comments

-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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.