Attaching an event listener to elements with a specified Class name

Currently facing a challenge where I am trying to implement a function that captures click events on squares. The objective is to capture the click event on every button with the square class.

import { Component, OnInit } from '@angular/core';
  
  @Component({
    selector: 'app-area',
    template: `
      <div id="statusArea" className="status">Next player: <span>X</span></div>
      <div id="winnerArea" className="winner">Winner: <span>None</span></div>
      <button id="reset">Reset</button>
      <section>
        <div class="row" *ngFor="let row of [1, 2, 3]">
          <button *ngFor="let col of [1, 2, 3]" class="square" style="width:40px;height:40px;"></button>
        </div>
      </section>
    `,
    styles: []
  })
  
  export class MainAppComponent implements OnInit {
  
    ngOnInit() { 
      const resetButton = document.getElementById('reset');
      const squares = Array.from(document.querySelectorAll('.square'));
  
      squares.forEach(square =>{
        square.addEventListener('click', function handleClicks(event){
          console.log('Button Clicked!');
        })
      });
  
      resetButton.addEventListener('click', function handleResetClick(event){
        console.log("Reset Clicked");
      });
    }
  }
  

Answer №1

It's important to understand that tinkering with the DOM in Angular is not recommended.

The framework already has built-in features for Adding Events, Properties Binding, and HTML selection (along with many other functionalities).

In this scenario, attempting to manually add the click event is unnecessary as you can simply use

(click)="onSquareClick()"
on your button element in the template.

<button *ngFor="let col of [1, 2, 3]" class="square" style="width:40px;height:40px;" (click)="onSquareClick()"></button>

If there is a genuine need to interact with the DOM, Angular offers Directives and some useful utilities for such situations.
Here you can explore some examples.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are some solutions for troubleshooting a laptop freeze when running JavaScript yarn tests?

Running the yarn test command results in all 20 CPU cores being fully occupied by Node.js, causing my laptop to freeze up. This issue is particularly troubling as many NodeJS/Electron apps such as Skype, MS Teams, and Slack are killed by the operating syst ...

Managing unpredictable fields within a TypeScript interface Let me known if you need further assistance

Currently, I am developing a web application using Angular and encountered an issue with the JSON data returned by a service call. The problem arises when the mapped JSON contains an Object within one of the fields with unpredictable content. How can I han ...

Tips to avoid conflicts between endpoints when building a REST API in an Express application

I am currently working with a REST API in an Express application to retrieve orders. http://localhost:2000/api/orders/chemists?orderBy=date&startDate=date1&endDate=date2 http://localhost:2000/api/orders/chemists?orderBy=chemist&startDate=date ...

"Incorporating splice in a for loop is causing issues and not functioning

I've been attempting to remove an item from an array, but for some reason, it's not working. Here's the code I'm using: vm.Continue = function () { $scope.invalidList = []; if (vm.errorexsist === true) { var table = doc ...

Tips for managing the number of items returned in a dataProvider using AS3

*Hey there! I'm looking to only display 100 items in a list component from a dataProvider, even if it contains more than 500 or even 1000 items. Specifically, I want the first 100 items with cameras on to be included, and then fill the rest to reach a ...

Comparison: NumberFormatter versus NumberFormat in PHP and JavaScript

My attempts to format currency seem to yield inconsistent results. Using PHP with the NumberFormatter class, here's a snippet of my code: $number = 5125.99; echo getInternationallyFormattedCurrency($number, 'tl-PH', 'PHP'); echo & ...

Leverage the power of v-model props in your Vue 3 component to efficiently retrieve API breakpoints

I am currently working on integrating the API breakpoints in my child component. These components are designed for my football web application. The breakpoints are sourced from: api-football My challenge lies in passing multiple prop values into a c ...

Looking to introduce Vue.js into an established SSR website?

Can Vue be used to create components that can be instantiated onto custom tags rendered by a PHP application, similar to "custom elements light"? While mounting the Vue instance onto the page root element seems to work, it appears that Vue uses the entire ...

Using keyof to access static properties within TypeScript classes

While experimenting with this TypeScript playground code sample, I encountered an issue with defining the greeterBuilderName variable. How can I specify that I want properties of the Greeter function itself (such as prototype, warm_greeter, etc.) when keyo ...

Acquire the S3 URL link for the uploaded file upon completion of the file upload process

Is there a way to securely upload and generate a public Amazon S3 URL for a PDF file when a user clicks on a specific link? I'd like to avoid exposing the actual link to the user by uploading it to S3. Here's a sample code snippet: module.expo ...

What are the steps to accessing validation errors using express-validator?

Recently, I delved into the world of express-validator to enhance my skills. Despite going through the documentation thoroughly, there's a query lingering in my mind that might have already been addressed in the docs. My confusion arises from needing ...

Leveraging a specific section of an HTML5 CSS3 Bootstrap template in a separate template

As I create my website using a combination of free templates, I often find myself needing to merge elements from different designs. One specific example is wanting to incorporate the "Client Logo Slider" component from template 2 into my original template. ...

Creating a series of spots arranged in a semi-transparent line using JavaScript for a unique canvas

My attempt at creating a highlighter is encountering issues with transparency The problem might be due to using lineCap=round, resulting in multiple dark spots appearing in a single line (which shouldn't happen). It's difficult to fully describe ...

Using the JQuery template with $.get function does not produce the desired result

Working on populating a table using a Jquery Template can be tricky. One challenge is incorporating a json file via an ajax call for the population process. $(document).ready(function() { var clientData; $.get("/webpro/webcad/lngetusuario", funct ...

Struggling to make vue-i18n function properly with nuxt generate?

In an effort to enhance my skills, I am creating a small Nuxt project from scratch. While the project runs smoothly on the local server, I have encountered an issue with the language switcher not updating the translation fields when using nuxt generate. U ...

iOS devices featuring the scroll function allows for seamless navigation and effortless

Here is the code snippet that I am using: $(document).scroll(function() { thedistance(); }); I would like thedistance() to trigger while a user is scrolling on an iOS device, however, it currently only fires after the scrolling has stopped, rather t ...

Preventing a particular CSS file from being applied to my Angular component

Currently, my modal component is built using bootstrap, but we encountered an issue with our project's CSS file which also utilizes the same classes as bootstrap (.Modal, .Modal-header). This conflicting styling was causing problems for the design of ...

Dealing with CORS and multiple headers

After setting up CORS for my web api project and deploying it to local IIS, I encountered an issue when trying to call a controller method from Angular. The error message displayed was as follows: SEC7128: Multiple Access-Control-Allow-Origin headers ar ...

What could be causing the issue when the selected option is being changed and the condition does not work

Whenever the selection in a select element is changed, the corresponding text should also change. Check out this Fiddle here. (function($) { 'use strict'; function updateResultText() { var s1_is_1 = $("#s1").value === '1', ...

The IP validation feature in the textbox is not performing as anticipated

My goal is to have a textbox that receives an IP address and validates it before submission. To achieve this, I've developed a JavaScript class called `validityCheck`. In my main Vue.js component, I aim to utilize this class to validate the input&apo ...