Reputation: 4049
I am getting a problem that when I am setting shadow as true in my component I am getting whole dom when any image(other element too) clicked instead of the element which is clicked.
How can I resolve this issue.
Thanks in advance
Upvotes: 2
Views: 4598
Reputation: 4049
Here is the answer:
@Listen('click')
onHandleClickEvent(ev) {
// This will give you the clicked element (composedPath()[0])
console.log('===== 31 =====', ev.composedPath()[0]);
}
Upvotes: 4
Reputation: 787
You can use the currentTarget property of the event arguments object which is passed to the event handler in order to get the element which was clicked. For example, look at the following code:
import { Component, Prop } from '@stencil/core';
@Component({
tag: 'my-component',
styleUrl: 'my-component.css',
shadow: true
})
export class MyComponent {
@Prop() first: string;
@Prop() middle: string;
@Prop() last: string;
constructor() {
this.imgClicked = this.imgClicked.bind(this);
}
format(): string {
return (
(this.first || '') +
(this.middle ? ` ${this.middle}` : '') +
(this.last ? ` ${this.last}` : '')
);
}
imgClicked(evt) {
console.log(evt.currentTarget);
}
render() {
return <div>Hello, World! I'm {this.format()}<img src="https://twitter.com/gilfink" onClick={this.imgClicked}/></div>;
}
}
In the code, the onClick handler (which is the imgClicked function) will print the image element which was clicked to the console.
Upvotes: 0