Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

359
Visualizações
How to get event.target as an object in Angular 2?

First, I'm sorry to my deficient english.

.

I want write code if click anywhere except .do-not-click-here, call myFunction().

So I wrote code like below.

document.addEventListener('click', (event) => {
  if(event.target.classList.includes('do-not-click-here')) {
    myFunction();
  }
)

But this code return error "Property 'classList' does not exist on type 'EventTarget'."

.

So I tried debugging through console.log.

.

When I tried console.log(event);

received event.target as a javascript object. (I want it)

.

When I tried console.log(event.target);

received event.target as an element(?). so event.target.classList is not working. (Maybe)

.

How to get event.target.classList?

or is there a better way than I thought for I wanted?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Other answers are good, this is just a more-angular-style alternative. You can create a global click listener in any of your components this way:

@HostListener('document:click', ['$event.target'])
onClick(element: HTMLElement) {
    if(element.classList.contains('do-not-click-here')) {
        myFunction();
    }
}
over 4 years ago · Santiago Trujillo Relatório

0

<button (click)="onClick($event)">click</button>

export class Component{


onClick(event){
   if(event.target.classList.contains('do-not-click-here')) {
    myFunction();
  }
}
}
over 4 years ago · Santiago Trujillo Relatório

0

document.addEventListener('click', (event) => {
  if(event.target.classList.contains('do-not-click-here')) {
    myFunction();
  }
)

use contains instead includes

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda