How to get event.target as an object in Angular 2?
Solution 1
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();
}
}
Solution 2
<button (click)="onClick($event)">click</button>
export class Component{
onClick(event){
if(event.target.classList.contains('do-not-click-here')) {
myFunction();
}
}
}
Solution 3
document.addEventListener('click', (event) => {
if(event.target.classList.contains('do-not-click-here')) {
myFunction();
}
)
use contains
instead includes
Related videos on Youtube
Comments
-
Byoth almost 2 years
First, I'm sorry to my deficient english.
.
I want write code if click anywhere except
.do-not-click-here
, callmyFunction()
.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(?). soevent.target.classList
is not working. (Maybe).
How to get
event.target.classList
?or is there a better way than I thought for I wanted?
-
Günter Zöchbauer about 7 yearsCan you try
(event.target as HTMLElement).classList...
?
-