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

守給你的承諾、 提交于 2019-11-27 14:50:35

Declarative event binding is only supported in static HTML in a components template.
If you want to subscribe to events of elements dynamically added, you need to do it imperatively.

elementRef.nativeElement.querySelector(...).addEventListener(...)

or similar.

If you want to be WebWorker-safe, you can inject the Renderer

constructor(private elementRef:ElementRef, private renderer:Renderer) {}

and use instead

this.renderer.listen(this.elementRef.nativeElement, 'click', (event) => { handleClick(event);});

to register an event handler.

see also Dynamically add event listener in Angular 2

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>

(2) Declare $

declare var $: any;

(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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!