Addeventlistener On Dynamically Created Elements Not Working
I want to add click events to images present in inner html. But when I try to add it, it won't work. Template Code myHtml; ngOnInit()
Solution 1:
You need to use ngAfterViewInit() to achieve this, I have modified the code and is working fine.
Please check the link https://stackblitz.com/edit/angular-7da7cd
Hope this helps.
Solution 2:
This may be due to restriction that event listener will be registered only for elements before page cycle starts. Did you try doing it more angular-ish way by Renderer2
this.renderer.listen('img', 'click', (evt) => {
console.log('Clicking the document', evt);
});
Solution 3:
Its not yet in the DOM. Do the same with ngAfterViewInit
:
ngAfterViewInit() {
const root = document.createElement('div');
root.innerHTML = this.getHtml();
const images = root.getElementsByTagName('img');
Array.prototype.forEach.call(images, (image: HTMLImageElement, i) => {
image.addEventListener('click', (event: any) => {
console.log('click', event);
});
});
this.myHtml = root.innerHTML;
}
Solution 4:
You can use elementRef
for specifying <img>
element. Then you can use the following to add event listener into all <img>
:
ngAfterViewInit() {
var elem = this.elementRef.nativeElement.querySelectorAll('img');
if (elem) {
elem.forEach(res => {
res.addEventListener('click', this.onclick.bind(this));
})
}
}
Note that:
onclick() {
alert("Image clicked");
}
is a custom function which you can customize. And don't forget to import { ElementRef } from '@angular/core';
More detail into AfterViewInit
, .bind
, the difference between ElementRef
and Renderer
Post a Comment for "Addeventlistener On Dynamically Created Elements Not Working"