简体   繁体   English

使用 Class 向元素添加 eventListener

[英]Adding a eventListener to elements with Class

i have this challenge and i cant figure out how can i implement a function to get the click event on the squares.我有这个挑战,我不知道如何实现 function 来获得方块上的点击事件。 I want to get the click event on every button with square class.我想用方形 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 btn = document.getElementById('reset')
    const squares = Array.from(document.querySelectorAll('.square'))

    squares.forEach(square =>{
      square.addEventListener('click', function handleClicks(event){
        console.log('botão clicado');
      })
    })

    btn.addEventListener('click', function handleClick(event){
      console.log("clicado");
    })
  }
}

Just to make sure that this is clear: You shouldn't be poking around with the DOM in Angular.只是为了确保这一点很清楚:您不应该在 Angular 中使用 DOM。

The framework already provides mechanisms for Adding Events, Properties Binding and HTML selection (among dozens of more things)该框架已经提供了添加事件、属性绑定和 HTML 选择的机制(还有很多东西)

In your case, you were trying to add the click event manually, but the framework got you covered by simply adding the (click)="onSquareClick()" to your button element in the template.在您的情况下,您试图手动添加单击事件,但框架通过简单地将(click)="onSquareClick()"添加到模板中的按钮元素来覆盖您。

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

If you really need to play with the DOM, Angular introduces the concept of Directives together with a few utilities that can be handy in such scenarios.如果你真的需要玩 DOM,Angular 引入了指令的概念以及一些在这种情况下可以派上用场的实用程序。
Here you can find some examples 在这里你可以找到一些例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM