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 elements
elements` 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)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.