1

I want to add click events to images present in inner html. But when I try to add it, it won't work.

Template

<div [innerHTML]="myHtml"></div>

Code

myHtml;

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

Here is the stackblitz

ProgrammerPer
  • 1,125
  • 1
  • 11
  • 26
Suhel
  • 927
  • 8
  • 19

4 Answers4

2

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.

Santhosh mp
  • 559
  • 7
  • 12
2

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';

Stackblitz Fork.

More detail into AfterViewInit, .bind, the difference between ElementRef and Renderer

Mukyuu
  • 6,436
  • 8
  • 40
  • 59
1

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

Docs : https://angular.io/api/core/Renderer2

Aravind Anil
  • 153
  • 1
  • 9
  • 1
    Thanks, this is also work, but instead of 'img' target good to send the nativeElement of the required element – Suhel Jan 22 '19 at 08:02
1

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;
  }
Julius Dzidzevičius
  • 10,775
  • 11
  • 36
  • 81