Angular2 - catch/subscribe to (click) event in dynamically added HTML

Viewed 16676

I'm attempting to inject a string that contains a (click) event into the Angular2 template. The string is dynamically retrieved from the back-end much after the DOM is loaded. No surprise here that Angular won't recognize the injected (click) event.

Example template:

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

Example string given from back-end:

var test = "When ready, <span (click)=\"itemClick($event)\">click me</span>."

Example function call in the Angular component:

itemClick(event) {
   debugger;
}


My next guess would be to try having Angular subscribe or catch a plain-old javascript event, so the string would then be:

var test = "When ready, <span onClick=\"itemClick($event)\">click me</span>."

Sure enough, I get an error that itemClick is not defined, so I know it's looking for that javascript function.

So question: How can I get Angular2 to subscribe to this event or function?

2 Answers

I had problems importing ElementRef in my service and did not want to pass Renderer reference there. This Service is about showing 'Loading...' dialog where after 3 seconds dynamic close button is attached. I found solution how to add click event for this button using jQuery. Hopefully this helps someone.

(1) Add jQuery to Angular 2 index.html file

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

enter image description here

(2) Declare $

declare var $: any;

enter image description here

(3) Use jQuery This is piece of code from my service:

 public async present() {
    this.isLoading = true;
    return await this.loadingController.create({message: 'Loading...'}).then(a => {
      a.present().then(() => {
        setTimeout(() => {
          a.message += '<ion-icon name="close-circle" class="alert-cancel-button"></ion-icon>';


          // Here starts jQuery usage
          $(a).click((clickedObject) => {
            if ($(clickedObject.target).hasClass('alert-cancel-button')) {
              this.dismiss();
            }
          });


        }, 3000);
      });
    });
  }

  public async dismiss() {
    return await this.loadingController.dismiss();
  }
  • By the way $('alert-cancel-button').click(() => this.dismiss()) didn't work.
Related