How to get event.target as an object in Angular 2? - javascript

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?

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

<button (click)="onClick($event)">click</button>
export class Component{
onClick(event){
if(event.target.classList.contains('do-not-click-here')) {
myFunction();
}
}
}

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

you can be REALLY angular use a class as a directive selector:
#Directive({
selector: '.do-not-click-here'
})
export class DoNotClickDirective {
#HostListener('click', ['$event'])
onClick(event: MouseEvent) {
console.log('dont click me!', event);
}
}
now everything with that class will run that function when clicked
blitz (check / click hello component for usage): https://stackblitz.com/edit/angular-7-master-zfzrrb?file=src/app/do-not-click.directive.ts

Related

prevent onclick event while changing radio button of primeng

Hi have simple radio buttons of primeng, while changing the choise, I have some logic on the onClick function, checking if the user changed some fields, if he changed I will show message if he sure he want to leave the choice of the radio button, if he will press "cancel" I want to cancel all the event of the onlick function and to undo to his last choise. but the event of the onclick not doing it, I checked all the function of java script. I tried now to add HostListener that if some boolean field(the one that said the user want to undo)it will stopImmediatePropagation. but on runtime the onclick function called and not the HostListener. some ideas what to do?
radio button
<p-radioButton name="treesDetailsType" [(ngModel)]="selectedType" formControlName="selectedType" (onClick)="onChangeType(type,$event)" class="treeDetails" value="{{type.id}}" label="{{type.desc}}" [disabled]="isReadOnly && type.id != data.selectedType"></p-radioButton>
the onclick function
onChangeType(type, event) {
let change = this.checkChanges(type, event);
if (change) {
//HERE I WANT TO CANCEL ALL THE CHANGE AND TO LEAVE THE FUNCTION
this.clickDisallowed = true;
}
else {
switch (type.id)
.....
}
}
the host listner
#HostListener('click', ['$event']) onClick(event) {
if (this.clickDisallowed) {
event.stopImmediatePropagation();
}
console.log(event);
}
Maybe you are using the hostlistener wrongly.
In the angular example it is used inside a directive
https://angular.io/api/core/HostListener
Try this example!
#Directive({selector: 'button[counting]'})
class CountClicks {
numberOfClicks = 0;
#HostListener('click', ['$event.target'])
onClick(btn) {
console.log('button', btn, 'number of clicks:', this.numberOfClicks++);
}
}
#Component({
selector: 'app',
template: '<button counting>Increment</button>',
})
class App {}

keydown firing multiple times when keydown (reactjs)

I am adding an event listener and checking if its level 1, but when I press the space key once, it fires 50times or more. Please help
document.addEventListener("keyup", function(e) {
if(level === 1){
if(e.code === "Space") {
console.log('space press');
click1();
}
}
});
Since this is tagged with React, given the code you have here and the issue you describe, it is almost certain that you are binding an event listener every render. Which means you are ending up with way more listeners than you want. What you need to do is use React when you are using React.
For example below, we have an input that logs on any keypress, and we also manually create an event listener. At first, when you type, you will get one log for each. However, once you click the button (triggering a rerender), you will start getting multiple "manual" events, but still the single "react" event:
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = { count: props.count };
}
inc() {
this.setState(prev => ({count: prev.count+1}));
}
render() {
document.addEventListener("keyup", function(e) {
console.log('manual space press');
});
return <div onKeyUp={(e) => {
console.log('React: space press');
}}>
<button onClick={() => this.inc()}>{this.state.count}</button>
<input />
</div>
}
}
ReactDOM.render(<Hello count={0}/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root'></div>
This is something called Event Bubblingwhich basically means that the event gets fired once on each parent element until it reached HTML.
you can learn about it here: https://dev.to/eladtzemach/event-capturing-and-bubbling-in-react-2ffg#:~:text=Event%20Bubbling%20and%20Capturing%20in%20React&text=Bubbling%20is%20as%20straightforward%20as,our%20example%20in%20the%20beginning.
you are able to prevent the default behavior but it's generally a good practice to leave it as is if you don't have a specific use for disabling it.
from the code snippet, I don't see why is this tagged with react but another reason for your problem is that you may be putting this code inside of your render() function or inside of any react life cycle function which is causing this snippet to run with each rerender leaving you with a punch of unwanted listeners which is not only functionality you don't want but also something that will slow down you app
overtime ie. until the user refresh the page.
useEffect(() => {
const handleEscape = (event) => {
if (event.keyCode === 27) {
console.log('Hello')
}
};
window.addEventListener('keydown', handleEscape);
return () => {
window.removeEventListener('keydown', handleEscape);
};
}, []);

addEventListener mouseEvent is not working in angular

I am trying to add addEventListener on some HTML canvas element which is created dynamically. earlier it was working fine, but now none of the event working. Code below I am using -
this.canvas.addEventListener('mousedown', (event) => {...});
Is there any another method to register mouse event/touch event to DOM element?
Stackblitz Example
Pls check your able to access the this.canvas in the class
The alternative are as below
1.method is to use plain javascript, grab the element by id and add an event to it
// Add event listener to table
var el = document.getElementById("outside");
el.addEventListener("click",yourCustomCallBackFunction);
2. method is to create a directive and use it for your canvas,sample code below
import { Directive, ElementRef, Renderer, HostListener } from '#angular/core';
#Directive({
selector: '[appChbgcolor]'
})
export class ChangeBgColorDirective {
constructor(private el: ElementRef, private renderer: Renderer) {
// this.ChangeBgColor('red');
}
#HostListener('mouseover') onMouseOver() {
this.ChangeBgColor('red');
}
#HostListener('click') onClick() {
window.alert('Host Element Clicked');
}
#HostListener('mouseleave') onMouseLeave() {
this.ChangeBgColor('black');
}
ChangeBgColor(color: string) {
this.renderer.setElementStyle(this.el.nativeElement, 'color', color);
}
}
and later on go ahead and put the directive to youe html
<div appChbgcolor>
<h3>{{title}}</h3>
</div>
Reference:
detailed description for hostListener
I got it working by making your event listener attach to the document itself.
changing it from
this.canvas.addEventListener('mousedown', (event) => {
console.log('mousedown called');
event.preventDefault();
this._setScratchPosition();
this.canvas.addEventListener('mousemove', this.scratching);
this.callbackFun();
});
to this:
document.addEventListener('mousedown', (event) => {
console.log('mousedown called');
event.preventDefault();
this._setScratchPosition();
document.addEventListener('mousemove', this.scratching);
this.callbackFun();
or:
window.addEventListener('mousedown', (event) => {
console.log('mousedown called');
event.preventDefault();
this._setScratchPosition();
window.addEventListener('mousemove', this.scratching);
this.callbackFun();
});
or more specifically
declare a new variable for instance
public c: any;
then add
this.c = document.getElementById('myCanvas');
this.c.addEventListener('scratch.move', () => {
this.percent = Number(this.getPercent().toFixed(2));
console.log('scratch.move called');
if (this.percent > 5) {
this.togglePrizeLabel();
}
});
and it works as advertised properly. You cannot directly reference a canvas object How do I add a simple onClick event handler to a canvas element?

Inconsistent addEventListerner behaviour angular 7

I am using innerHTML binding to create dynamic a tag as in below code:
<span *ngIf="msg" [innerHTML]="msg | sanitizeHtml"></span>
In .ts I am trying to add click event using addEventListerner:
ngAfterViewInit() {
this.elements = this.elem.nativeElement.querySelectorAll('.tradebtn');
if (this.elements && this.elements.length > 0) {
this.elements.forEach((f) => {
console.log(f)
f.addEventListener('click', (event) => {
console.log(event)
});
});
}
}
I get elementselements` list to add event listener. Click event listener works sometimes but doesn't work at most of the times.
I am perplexed at this behavior. I also tried to enclose the code setTimeout() but no luck.
You should use #HostListener to handle event.
Add condition event.target.matches('.tradebtn') to check element source.
#HostListener('document:click', ['$event'])
onclick(event) {
if(event.target.matches('.tradebtn')) {
console.log(event)
}
}

Jquery/Javascript Add class if X class is not exist

I am new here, sorry if I do some mistake with this question.
I have a HTML code.
hit me
with this function i can add class two in class one
$(document).ready(function () {
$('a#foo').click(function(){
$('.one').toggleClass('two');
});
});
but how if I want to add class two if class two is not exist and do other function if class two is exist?
maybe like this,
hit me
i klik hit me and jquery is add class two,
hit me
but when I klick hit me again, class two is not removed and because class is exist, i create other function based on class two is exist.
lets say like this,
i klik hit me
hit me
<div id="blah" class=""*>lorem</div>
then
hit me
<div id="blah" class=""*>lorem</div>
and klik hit me again.
hit me
<div id="foo" class="blah2">lorem</div>
can you give me code or google suggest keyword or link, because I confused what i must search first.
thanks for adv,
sorry for my Grammer, i cant speak/write English well, if any wrong grammer or language please correct me.
Using the hasClass() method and you're examples:
$(document).ready(function () {
$('a#foo').click(function(){
if ($(this).hasClass('two')) {
$('#blah').addClass('blah2');
} else {
$(this).addClass('two');
}
});
});
Use jQuery hasClass method .
$(document).ready(function () {
$('a#foo').click(function(){
if ($(this).hasClass('two')) {
doSomething();
} else {
$('.one').addClass('two');
}
});
});
i'm a little confused as to what exactly you want to do, but I think you need to look into .hasClass() for starters.
$(document).ready(function () {
$('a#foo').click(function(){
if ($('.one').hasClass('two')) {
// do stuff you want to do if element already has class "two"
}
else {
// do stuff if it doesnt already have class "two"
}
});
});
I am guessing at your exact needs, but I hope that my assumptions weren't too far off base.
Given HTML like this:
hit me
<div id="change" class="blah1"></div>
And JS Like this:
$(document).ready(function () {
$('a#foo').click(function(e){
e.preventDefault();
var changeDiv = $('#change');
if ($(this).hasClass('two')) {
changeDiv.addClass('blah2').removeClass('blah1');
changeDiv.html('<p>Blah 2</p>');
} else {
changeDiv.addClass('blah1').removeClass('blah2');
changeDiv.html('<p>Blah 1</p>');
}
$('.one').toggleClass('two');
});
});
You will be able to toggle your link's class and change or update another div based on the class of your link when clicked.
You can see this code working at http://jsfiddle.net/PTdLQ/4/
Another way to look at this is to check if the given class exists in the dom. Therefore, one can use the following:
$(document).ready(function () {
$('a#foo').click(function(){
if ($('.two').length) {
//there is a class two
SomeFunction();
} else {
//there is no class two
SomeOtherFunction();
}
});
});
Hope I typed it right
Use this code:
<script>
$(document).ready(function () {
if(!$('#mydiv').hasClass('myclass')) {
$('#mydiv').addClass('myclass');
}
});
</script>

Categories

Resources